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?
-
Just open the template file and return it as a string.OneCricketeer– OneCricketeer2015-10-28 21:50:18 +00:00Commented Oct 28, 2015 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– Faminator2015-10-28 21:51:26 +00:00Commented Oct 28, 2015 at 21:51
-
Is that not your question? How can I render the text of a template simply?OneCricketeer– OneCricketeer2015-10-28 21:53:15 +00:00Commented Oct 28, 2015 at 21:53
-
Yeah, but it doesn't handle the things in {...}Faminator– Faminator2015-10-28 21:54:19 +00:00Commented Oct 28, 2015 at 21:54
-
So i want a simple solution not a simple templateFaminator– Faminator2015-10-28 21:54:32 +00:00Commented Oct 28, 2015 at 21:54
|
Show 1 more comment
4 Answers
You can use render_template_string:
>>> from flask import render_template_string
>>> render_template_string('hello {{ what }}', what='world')
'hello world'
2 Comments
Sharvari Gc
this answer gives an error: AttributeError: 'NoneType' object has no attribute 'app'
Jean Monet
@SharvariGc in that case you need to use it inside a context:
with app.app_context(): .... See here: stackoverflow.com/a/50927259/11750716Actually you can call jinja2 render function directly:
jinja2.Template("I am {{ var }}").render(**kargs)
When not working with flask, this is useful
1 Comment
Sean Pianka
This seems to be the simplest way without requiring Flask
you can use from_string
template = "text {{ hello }}"
print app.jinja_env.from_string(template).render(hello='Hello')
>> text Hello
2 Comments
ThiefMaster
Since he's using Flask he can just use
render_template_string (imported from Flask)Faminator
I can't tick both answers as right. Your answer is good too ;)
Taken from What's the easiest way to escape HTML in Python.
import cgi
rendered = render_template('template.html')
return cgi.escape(rendered)
2 Comments
ThiefMaster
What has HTML escaping to do with this question?
OneCricketeer
This returns the rendered HTML file template as a string. The other answers just do simple template strings. @ThiefMaster