Python 如何在 Jinja2 模板中包含 HTML 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22860085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I include a HTML file in a Jinja2 template?
提问by quapka
I am using Flask micro-framework for my server which uses Jinja templates.
我正在为使用 Jinja 模板的服务器使用 Flask 微框架。
I have a parent template.html
and some children templates called child1.html
and child2.html
, some of these children templates are pretty large HTML files and I would like to somehow split them for better lucidity over my work.
我有一个父template.html
模板和一些名为child1.html
and 的子模板child2.html
,其中一些子模板是非常大的 HTML 文件,我想以某种方式将它们分开,以便更好地了解我的工作。
Contents of my main.py
script:
我的main.py
脚本内容:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
@app.route('/<task>')
def home(task=''):
return render_template('child1.html', task=task)
app.run()
The simplified template.html
:
简化的template.html
:
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="container">
{% block content %}{% endblock %}
</div>
</body>
</html>
The magic is in child1.html
:
神奇之处在于child1.html
:
{% extends 'template.html' %}
{% block content %}
{% if task == 'content1' %}
<!-- include content1.html -->
{% endif %}
{% if task == 'content2' %}
<!-- include content2.html -->
{% endif %}
{% endblock %}
Instead of the comments:
而不是评论:
<!-- include content1.html -->
I have a lot of html text, and it is very hard to keep track of changes and not to make some mistakes, which are then pretty hard to find and correct.
我有很多 html 文本,很难跟踪更改并且不犯一些错误,然后很难找到和纠正这些错误。
I'd like to just load the content1.html
instead of writing it all in child1.html
.
我只想加载content1.html
而不是全部写入child1.html
.
I came across this question, but I had problems implementing it.
我遇到了这个问题,但我在实施它时遇到了问题。
I think Jinja2 might have a better tool for that.
我认为 Jinja2 可能有一个更好的工具。
NOTE:The code above might not be working properly, I just wrote it to lustrate the problem.
注意:上面的代码可能无法正常工作,我只是编写它来解决问题。
采纳答案by msvalkon
Use the jinja2 {% include %}
directive.
使用 jinja2{% include %}
指令。
{% extends 'template.html' %}
{% block content %}
{% if task == 'content1' %}
{% include 'content1.html' %}
{% endif %}
{% if task == 'content2' %}
{% include 'content2.html' %}
{% endif %}
{% endblock %}
This will include the content from the correct content-file.
这将包括来自正确内容文件的内容。