Python Flask Render Text from Variable like render_template

笑着哭i 提交于 2019-12-17 06:52:24

问题


I know the flask function render_template. I have to give the file name of the template. But now I want to render the string of a template (that is the content of the template). That makes sense. but I don't want to explain now why. How can I render the text of a template simply?


回答1:


You can use render_template_string:

>>> from flask import render_template_string
>>> render_template_string('hello {{ what }}', what='world')
'hello world'



回答2:


you can use from_string

template = "text {{ hello }}"
print app.jinja_env.from_string(template).render(hello='Hello')

>> text Hello



回答3:


Actually you can call jinja2 render function directly:

jinja2.Template("I am {{ var }}").render(**kargs)

When not working with flask, this is useful




回答4:


Taken from What's the easiest way to escape HTML in Python.

import cgi
rendered = render_template('template.html')
return cgi.escape(rendered)


来源:https://stackoverflow.com/questions/33402163/python-flask-render-text-from-variable-like-render-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!