Skip to content

Dynamic content

Manish Sah edited this page Sep 17, 2020 · 1 revision

using jinja to update html files dynamically

Previously we were able to return html pages instead of strings. There is still an issue. The pages are static.

We can change the page's content dynamically using jinja. Jinja is a templating language for python.

Jinja comes along with the flask so we don't need to install it manually

we can achieve this in following steps:

  • pass data to an html file using render_template
  • use jinja to change the content of the page according to the data received

example

@app.route("/about")
def about():
    return render_template('about.html', title_name='about-page')

render_template takes key-value pair to pass data to the corresponding html page. lets pass title in our about page so that title of the page can be changed dynamically.

our about.html page will be like this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% if title_name %}
        <title>{{ title_name }}</title>
    {% else %}
        <title>Title</title>
    {% endif %}
</head>
<body>
<h1>This is the about page</h1>

</body>
</html>

Here, {{}} and {%%} are jinja syntax.

  • {{ variable_name }} is used for displaying values
  • {%%} is used for control statements such as for loops, if-else

Note: The key(variable) passed in render_template and the key used in html page must be same.

Implementation can be found over this commit

Clone this wiki locally