python - 如何查看 flask 最终输出的jinja模板
迷茫
迷茫 2017-04-18 10:22:54
0
2
666

我在模板中写了个 for 循环,类似 {% for n in Data %} 这样的,然后我想看 flask 把这个 for 循环展开后最终生成的模板文件,应该怎么去查看? 我不要通过浏览器查看源代码的方式。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
刘奇

flask uses the jinja module, just call it directly, as follows

In [5]: from jinja2 import Template

In [6]: template = Template('{% for n in Data %} {{ n}} {% endfor %}')

In [7]: Data = range(10)
   ...: 

In [8]: template.render(Data=Data)
   ...: 
Out[8]: u' 0  1  2  3  4  5  6  7  8  9 '

Reference: http://docs.jinkan.org/docs/j...

Ty80

Using render_template_string 即可, 传参方式和 render_template is similar, except that the first parameter is the read template content, not the template file path
The sample code is as follows (short demonstration, no routing is written, directly use app_context to simulate access):

from flask import (
    Flask,
    render_template_string
)

app = Flask(__name__)
tpl_args = {
    'Data': [1, 2, 3, 4, 5]
}
with app.app_context():
    result = render_template_string('{% for n in Data %} {{ n }} {% endfor %}', **tpl_args)
    print(result)

The output is as follows:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template