19

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)

doru
  • 9,022
  • 2
  • 33
  • 43
Max L.
  • 9,774
  • 15
  • 56
  • 86

4 Answers4

29

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

Shankar ARUL
  • 12,642
  • 11
  • 68
  • 69
13

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)
davidism
  • 121,510
  • 29
  • 395
  • 339
1

What I use is this code:

import jinja2
template_values = {
  'value_name_in_html': value_name_in_python,   
}

template = JINJA_ENVIRONMENT.get_template("file_patch")
self.response.write(template.render(template_values))
Y2H
  • 2,419
  • 1
  • 19
  • 37
  • 1
    It's complaining JINJA_ENVIRONMENT is not set. How should I set it ? – blissweb Aug 12 '20 at 02:58
  • Hi @blissweb, I am sorry I have not used Jinja in like 4 years so this info is not at the top of my head at the moment. If I get a chance later today I’ll look at it and get back to you. – Y2H Aug 12 '20 at 08:13
0

You could use this simple steps to create and render a Jinja HTML template without using Flask. I use it to create email newsletter templates for my WordPress blog:

from jinja2 import Template

# Create a template string
template_string = """
<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>
"""

# Create a template object from the string
template = Template(template_string)

# Render the template with context data
rendered_template = template.render(title="My Example Page", name="John Doe")

# Print the rendered template
print(rendered_template)
devtonic
  • 1
  • 3