Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render jinja2 template without a Flask context

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)

like image 663
Max L. Avatar asked May 21 '15 19:05

Max L.


People also ask

What is templating with Jinja2 in flask?

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.

Can We render HTML string with Jinja2 without using Jinja2?

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.

How to include variables in Jinja render_template?

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:

How to add content to Jinja2 template in Python?

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).


2 Answers

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

like image 187
Shankar ARUL Avatar answered Oct 14 '22 08:10

Shankar ARUL


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)
like image 26
davidism Avatar answered Oct 14 '22 08:10

davidism