Creating static HTML pages with Jinja
Now we use some of the above-mentioned concepts to render a static html page that renders the table of a number. To render an HTML page, we just need to have the HTML markup inside the Jinja Template where required. We finally save the rendered text to an external file with a .html extension. Here is an example that creates an HTML page with the table of a given number.
Create a template with the following content and save it as “webTable.jinja” in the jinjaTests folder.
<!DOCTYPE html>
<html>
<head><title>Table of {{tableOf}}</title></head>
<body>
<h2>Table of {{tableOf}} rendered with Jinja -</h2>
{% for i in range(1,11) -%}
<p>{{tableOf}} x {{i}} = {{tableOf * i}}</p>
{%- endfor %}
</body>
</html>
Create a python file to render the above template and save it as “webTable.py” in the jinjaTests folder. Here are the contents of the file –
Python3
from jinja2 import Environment, FileSystemLoader env = Environment(loader = FileSystemLoader( 'templates' )) template = env.get_template( 'webTable.jinja' ) with open ( "renders/output.html" , 'w' ) as f: print (template.render(tableOf = 5 ), file = f) |
Running the above file produces a file named “output.html” in renders folder. You can check it out by opening it with a web browser. The output –
Try to understand the above program based on past concepts for practice.
Getting started with Jinja Template
This article introduces Jinja and then describes the basics of working with it which includes how to render templates using Jinja and Python3, passing data to the template through arguments, and basic Jinja syntax (delimiters, expressions, control structures – decisions and loops). A few examples including creating a simple static HTML page are presented.