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?
Asked
Active
Viewed 3.2k times
28
-
Just open the template file and return it as a string. – OneCricketeer Oct 28 '15 at 21:50
-
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 Oct 28 '15 at 21:51
-
Is that not your question? _How can I render the text of a template simply?_ – OneCricketeer Oct 28 '15 at 21:53
-
Yeah, but it doesn't handle the things in {...} – Faminator Oct 28 '15 at 21:54
-
So i want a simple solution not a simple template – Faminator Oct 28 '15 at 21:54
-
post your code please – oz123 Oct 28 '15 at 21:59
4 Answers
56
You can use render_template_string
:
>>> from flask import render_template_string
>>> render_template_string('hello {{ what }}', what='world')
'hello world'

mskfisher
- 3,291
- 4
- 35
- 48

ThiefMaster
- 310,957
- 84
- 592
- 636
-
1this answer gives an error: AttributeError: 'NoneType' object has no attribute 'app' – Sharvari Gc Oct 20 '20 at 07:26
-
@SharvariGc in that case you need to use it inside a context: `with app.app_context(): ...`. See here: https://stackoverflow.com/a/50927259/11750716 – Jean Monet Jun 13 '21 at 22:06
3
you can use from_string
template = "text {{ hello }}"
print app.jinja_env.from_string(template).render(hello='Hello')
>> text Hello

r-m-n
- 14,192
- 4
- 69
- 68
-
1Since he's using Flask he can just use `render_template_string` (imported from Flask) – ThiefMaster Oct 28 '15 at 23:07
-
2
Actually you can call jinja2 render function directly:
jinja2.Template("I am {{ var }}").render(**kargs)
When not working with flask, this is useful

duan
- 8,515
- 3
- 48
- 70
0
Taken from What's the easiest way to escape HTML in Python.
import cgi
rendered = render_template('template.html')
return cgi.escape(rendered)

Community
- 1
- 1

OneCricketeer
- 179,855
- 19
- 132
- 245
-
4
-
This returns the rendered HTML file template as a string. The other answers just do simple template strings. @ThiefMaster – OneCricketeer Oct 29 '15 at 00:54