Tech Monger

Programming, Web Development and Computer Science.

Skip to main content| Skip to information by topic

Dynamically Render Static HTML with Jinja2 in Python

Due to various reasons you might want to render dynamic html content outside of your web application. For example to create the html email body. Also you might want to use jinja2 with web framework which does not have inbuilt support for it. Below we will explain how to use jinja2 as standalone utility in python script with the help of an example code.

Install Jinja2 Library

Install jinja2 with pip. It is recommended to install it in virtual environment.

pip install jinja2

Create Jinja2 Template String

Before rendering jinja2 template you should have template string ready. You can either put content inside text file template.html or you can directly define it in python code as string. (Not recommended). Below is the simple template file with one liner Hello Template.

template.html

Hello {{ name }}!!!

Render Template as HTML String

from jinja2 import Template

# Get File Content in String
jinja2_template_string = open("template.html", 'rb').read()

# Create Template Object
template = Template(jinja2_template_string)

# Render HTML Template String
html_template_string = template.render(name = "John")
print html_template_string

Hello John

Conclusion

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.

Tagged Under : Jinja2 Python