29

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?

6
  • Just open the template file and return it as a string. Commented 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. Commented Oct 28, 2015 at 21:51
  • Is that not your question? How can I render the text of a template simply? Commented Oct 28, 2015 at 21:53
  • Yeah, but it doesn't handle the things in {...} Commented Oct 28, 2015 at 21:54
  • So i want a simple solution not a simple template Commented Oct 28, 2015 at 21:54

4 Answers 4

60

You can use render_template_string:

>>> from flask import render_template_string
>>> render_template_string('hello {{ what }}', what='world')
'hello world'
Sign up to request clarification or add additional context in comments.

2 Comments

this answer gives an error: AttributeError: 'NoneType' object has no attribute 'app'
@SharvariGc in that case you need to use it inside a context: with app.app_context(): .... See here: stackoverflow.com/a/50927259/11750716
4

Actually you can call jinja2 render function directly:

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

When not working with flask, this is useful

1 Comment

This seems to be the simplest way without requiring Flask
3

you can use from_string

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

>> text Hello

2 Comments

Since he's using Flask he can just use render_template_string (imported from Flask)
I can't tick both answers as right. Your answer is good too ;)
-1

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

What has HTML escaping to do with this question?
This returns the rendered HTML file template as a string. The other answers just do simple template strings. @ThiefMaster

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.