在Jinja2模板中包含html文件 [英] Include html file in Jinja2 template
问题描述
我使用Flask微型框架作为使用Jinja模板的服务器。我有父母template.html和一些孩子child1.html,child2.html。其中一些孩子是相当大的HTML文件,我想以某种方式分开他们,以更好地清理我的工作。
main.py:
from flask import Flask,request,render_template
$ b $ app = Flask(__ name__)
@app .route('/')
@ app.route('/< task>')
def home(task =''):
return render_template('child1.html',任务=任务)
app.run()
简化的模板。 html:
<!DOCTYPE html>
< html>
< head>
< / head>
< body>
< div class =container>
{%block content%}
{%endblock%}
< / div>
< / body>
< / html>
神奇的是在child1.html中:
{%extends'template.html'%}
{%block content%}
{%if task =='content1'%}
<! - include content1.html - >
{%endif%}
{%if task =='content2'%}
<! - include content2.html - >
{%endif%}
{%endblock%}
评论
<! - include content1.html - >
我有很多html文本。要记住变化是很困难的,不要犯一些很难找到和纠正的错误。所以我想只加载content1.html,而不是全部写在child1.html中。我遇到了这个问题在HTML文件中包含另一个HTML文件,但是我在执行时遇到问题。我认为Jinja2可能有更好的工具。
注意。
上面的代码可能工作不正常,编写它来解释这个问题。 解决方案
使用jinja2 {%include%}
指令
{%extends'template.html'%}
{%block content%}
{%if task =='content1'%}
{%include'content1.html'%}
{%endif%}
{%if task =='content2'%}
{%include'content2.html'%}
{%endif%}
{%endblock%}
从正确的内容文件。
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.
the 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:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
And the magic is in 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.
Note. The code above might not be working properly, I just wrote it to ilustrate the problem.
Use the jinja2 {% include %}
directive.
{% 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.
这篇关于在Jinja2模板中包含html文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!