28

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?

r-m-n
  • 14,192
  • 4
  • 69
  • 68
Faminator
  • 888
  • 1
  • 10
  • 16

4 Answers4

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
  • 1
    this 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
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