我在模板中写了个 for 循环,类似 {% for n in Data %}
这样的,然后我想看 flask 把这个 for 循环展开后最终生成的模板文件,应该怎么去查看? 我不要通过浏览器查看源代码的方式。
怪我咯2017-04-18 10:24:54
flask 使用jinja模組,直接呼叫就可以了, 如下
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 '
參考:http://docs.jinkan.org/docs/j...
PHP中文网2017-04-18 10:24:54
使用 render_template_string
即可, 传参方式和 render_template
類似,只是第一個參數為讀取的模板內容, 而不是模板文件路徑
示例代碼如下(簡短演示,就不寫路由, 直接用 app_context 模擬訪問):
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)
輸出如下: