Jinja2 带有组件的模板?块?模板?

问题描述 投票:0回答:2

关于 jinja2 模板的一个小问题: 我想创建一个可重用的模板来包含然后覆盖块。宏不会让我轻松地编写 HTML 垃圾作为参数,不是吗?假设我想多次重复使用包含,并且在我想要动态分配的块中使用大量 HTML 垃圾 我该怎么做?

我猜肯定不是用宏,还是我错了?

{% render_foo('bar',2) %}
还好

{% render_foo('<table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc') %}
已经不行了是吗

“你到底想做什么?”

是的,我告诉过你,我有办法为我的数据创建容器。容器始终是相同的。每次使用时内容都完全不同。一次一桌。曾经是引导组件。一次表格。

周围的元素总是一样的

为了重现这个简单的错误,我就是这样做的:

 {% include 'full_section.html' %}
  {% block fullsection %} <table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc{% endblock %}

  {% include 'full_section.html' %}
  {% block fullsection %} <form>//some cool LONG big form </form>{% endblock %}

full_section.html
内容只是为了完整性,实际情况要复杂得多

<div class="my_cool_full_section">
{% block full_section %}{% endblock %}
</div>

TemplateAssertionError:块“fullsection”定义了两次

django jinja2
2个回答
6
投票

我在 jinja2 文档中找到了隐藏得很好的答案

http://jinja.pocoo.org/docs/2.9/templates/#block-assignments

因此您可以使用宏和块分配,例如像这样:

{% set section_content %} <table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table> <table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table> <table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table> {% endset %} {{ render_full_size_section(section_content) }} {% set section_content %} aaaaaaaaaaa {% endset %} {{ render_full_size_section(section_content) }}

想知道 2.8 之前他们在做什么......黑暗黑暗的中年

然后在宏中:

{% macro render_full_size_section(content) %} <div class="mycoolsection"> {{ content | safe }} </div> {% endmacro %}
    

0
投票
使用

jinja 调用标签将宏与其他宏或 html 内容嵌套

{% call render_dialog('Hello World') %} This is a simple dialog rendered by using a macro and a call block. {% endcall %}
或者,您可以将 HTML 设置为 

set tag block 并将其作为宏 prop 传递

{% set navigation_html %} <li><a href="/">Index</a> <li><a href="/downloads">Downloads</a> {% endset %} {{ my_macro(navigation_html) }}
    
© www.soinside.com 2019 - 2024. All rights reserved.