Base.html扩展到create.html
base.html文件
{% block title %}Index{% endblock %}
{% block body %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock %}
create.html上
{% extends "base.html" %}
{% block title %}Index1{% endblock %}
{% block content %}
<p class="important">
first message.
</p>
{% endblock %}
{% block title %}Index2{% endblock %}
{% block content %}
<p class="important">
second message.
</p>
{% endblock %}
...
{% block title %}Indexn{% endblock %}
{% block content %}
<p class="important">
nth message.
</p>
{% endblock %}
如何重复扩展base.html并重复模板在单个文件上?任何建议。
答案 0 :(得分:4)
您可以使用宏标记,您的模板将如下所示
{% macro create_block(title, message) %}
<h1>{{title}}</h1>
<p class="important">
{{message}}
</p>
{% endmacro %}
{% for title, message in list %}
{{ create_block(title, message) }}
{% endfor %}
我测试它,这是我的脚本:
from jinja2 import Template
titles = ['1 title', '2 title']
messages = ['1 message', '2 message']
template = Template("""
{% macro create_block(title, message) %}
<h1>{{title}}</h1>
<p class="important">
{{message}}
</p>
{% endmacro %}
{% for title, message in list %}
{{ create_block(title, message) }}
{% endfor %}
""")
print template.render(list=zip(titles, messages))
这是我的输出
<h1>1 title</h1>
<p class="important">
1 message
</p>
<h1>2 title</h1>
<p class="important">
2 message
</p>
我希望它能解决你的问题