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?
27
votes
Just open the template file and return it as a string.
- OneCricketeer
But if i do that (i have flask-bootstrap extension installed) it will give me these things: {% extends "bootstrap/base.html" %} etc. as plain text and not handled.
- Faminator
Is that not your question? How can I render the text of a template simply?
- OneCricketeer
Yeah, but it doesn't handle the things in {...}
- Faminator
So i want a simple solution not a simple template
- Faminator
4 Answers
51
votes
You can use render_template_string:
>>> from flask import render_template_string
>>> render_template_string('hello {{ what }}', what='world')
'hello world'
2
votes
you can use from_string
template = "text {{ hello }}"
print app.jinja_env.from_string(template).render(hello='Hello')
>> text Hello
2
votes
0
votes
Taken from What's the easiest way to escape HTML in Python.
import cgi
rendered = render_template('template.html')
return cgi.escape(rendered)