I have a Flask application that calls flask.render_template
without problems when it is invoked from a flask http request
.
I need the same method to work outside of flask (from a python back end program)
resolved_template = render_template(template_relative_path, **kwargs)
I could use the jinja2 api
, but I would like the same method to work, in both contexts (flask and command line)
This post is part of a series called Templating With Jinja2 in Flask . Jinja2 is a template engine written in pure Python. It provides a Django -inspired non-XML syntax but supports inline expressions and an optional sandboxed environment. It is small but fast, apart from being an easy-to-use standalone template engine.
We learned how can we render html string with jinja2 without using it in the context of specific web framework like Flask. Depending on your requirement it could have multiple use cases such as preparing dynamic html mail body or to dynamically generate static html pages from python.
You can then interpolate , and Jinja will be able to find the correct value from there. If you want to include variables in every template you render, without having to pass them manually as keyword arguments to render_template, then you can use a context processor, like so:
Before rendering jinja2 template you should have template string ready. You can either put content inside text file template.htmlor you can directly define it in python code as string. (Not recommended).
If you want to completely bypass flask
and use purely Jinja
for rendering your template, you can do as such
import jinja2
def render_jinja_html(template_loc,file_name,**context):
return jinja2.Environment(
loader=jinja2.FileSystemLoader(template_loc+'/')
).get_template(file_name).render(context)
And then you can call this function to render your html
You need to render it in an app context. Import your app in your backend code and do the following.
with app.app_context():
data = render_template(path, **context)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With