将HTML传递到Jinja宏

Flo*_*aun 3 html jinja2

我的页面上有许多Bootstrap模态,除了标识符和实际内容外,它们总是具有相同的标记。

为了最大程度地减少这些模式的大量重复代码,我想构建一个Jinja宏,通过一个简单的调用即可吐出模式的整个HTML标记,例如:

{# macros/modal_template.jinja2 #}

{% macro print_modal(id, title, body_content) %}
  <div class="modal fade" id="{{ id }}" tabindex="-1">
    <div class="modal-dialog">
       <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
          <h4 class="modal-title">{{ title }}</h4>
        </div>
        <div class="modal-body">
          {{ body_content }}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
{% endmacro %}


{# my_page.jinja2 #}

{% from "macros/modal_template.jinja2" import print_modal %}
<html>
<body>
  {{ print_modal("description-modal", "Description", "Lorem Ipsum") }}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

到目前为止,这几乎是很容易的,但是图像 body_content不是纯字符串,而是复杂的HTML表单或带有文本样式HTML的超长文本。我正在努力找到解决这个问题的好方法。

到目前为止,我想到的唯一可行的解​​决方案是将内容作为字符串传递并使用 {{ body_content|safe }},但是将复杂的标记放入字符串中既丑陋又不舒服。

你们有什么好主意吗?

mcl*_*lee 6

答案有点延迟-我刚刚在搜索您的问题时碰到了同样的事情,但我发现了:

您可以做的是像这样利用jinjas call / caller()功能。

{% macro print_modal(id, title) %}
  <div class="modal fade" id="{{ id }}" tabindex="-1">
    <div class="modal-dialog">
       <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
          <h4 class="modal-title">{{ title }}</h4>
        </div>
        <div class="modal-body">
          {{ caller() }} <---- {# Look at me! #}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)

当您使用宏时

{% call print_modal(someId, someTitle) %}
    {# whatever you put in here will be placed into the {{caller()}} line #}
    {# for example #}
    <h1>HELLO WORLD</h1> {# Will format an h1 into the caller block #}
{% endcall %}
Run Code Online (Sandbox Code Playgroud)