I am using Flask microframework for my server which uses Jinja templates. I have parent template.html and some childs child1.html, child2.html. Some of these childs are pretty large html files and I would like to somehow split them for better lucidity over my work.
我正在使用Flask微框架为我的服务器使用Jinja模板。我有父模板和一些孩子child1.html,child2.html。其中一些孩子是相当大的html文件,我想以某种方式拆分它们以便更好地清理我的工作。
the main.py:
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>
And 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. So I would like to just load the content1.html instead of writing it all in child1.html. I came across this question Include another HTML file in a HTML file , but I had problems implementing it. I think Jinja2 might have a better tool for that.
我有很多HTML文字。并且很难跟踪变化而不是犯一些错误,这些错误很难找到并纠正。所以我想加载content1.html而不是在child1.html中编写所有内容。我遇到了这个问题在HTML文件中包含另一个HTML文件,但我在实现它时遇到了问题。我认为Jinja2可能有更好的工具。
Note. The code above might not be working properly, I just wrote it to ilustrate the problem.
注意。上面的代码可能无法正常工作,我只是写它来说明问题。
2 个解决方案
#1
107
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.
这将包括来自正确内容文件的内容。
#1
107
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.
这将包括来自正确内容文件的内容。