SoFunction
Updated on 2024-11-17

Getting Started with Jinja templates for flask framework in python

Flask and Django come with the powerful Jinja template language.

For those of you who haven't come across template languages before, these are basically languages that contain variables that are replaced with actual values when the HTML is ready to be rendered.

These variables are placed before tags or separators. For example, Jinja templates use {% ... %} denotes a loop.{{ ... }} Indicates that the result of an expression operation is returned.

Jinja templates are actually html files. They are usually placed in the/templates directory

1、Quick experience

Before running the various demos below, make sure you have Jinja installed (pip install jinja2).

>>> from jinja2 import Template
>>> t = Template("Hello {{ something }}!")
>>> (something="World")
u'Hello World!'

>>> t = Template("My favorite numbers: {% for n in range(1,10) %}{{n}} " "{% endfor %}")
>>> ()
u'My favorite numbers: 1 2 3 4 5 6 7 8 9 '

This demo shows how variables (expressions) in a template are eventually replaced and rendered.

2、Flask minimum DEMO

The entire reference code is available here:HERE

However, the blogger suggests following the steps below step by step:

1) Install flask

➜  pip install flask

2) Create the project directory structure:

➜  mkdir flask_example
➜  cd flask_example 
➜  mkdir templates
➜  cd ..
➜  touch 
➜  touch 

3) Preparation

from flask import Flask, render_template
app = Flask(__name__)
@("/")
def template_test():
    return render_template('', my_string="Wheeeee!", my_list=[0,1,2,3,4,5])
if __name__ == '__main__':
    (debug=True)

Here, we create a/ route, when we access the server root route, it is passed through therender_template commander-in-chief (military) Rendering, wheremy_string cap (a poem)my_list is the actual value that is ready to be passed to the template.

4) Writing templates

In the templates directory, create a :

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/bootstrap/3.0.0/css/" rel="stylesheet" media="screen">
    <style type="text/css">
      .container {
        max-width: 500px;
        padding-top: 100px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <p>My string: {{my_string}}</p>
      <p>Value from the list: {{my_list[3]}}</p>
      <p>Loop through the list:</p>
      <ul>
        {% for n in my_list %}
        <li>{{n}}</li>
        {% endfor %}
      </ul>
    </div>
    <script src="/jquery-1.10."></script>
    <script src="/bootstrap/3.0.0/js/"></script>
  </body>
</html>

(5) Running to observe the effect

➜  python 

The effect is as follows:

As you can see, my_string, my_list[3] are replaced in the template and a for loop statement is used to generate a list.

3、Template inheritance

Templates typically utilize inheritance, which consists of a single base template that defines the basic structure of all subsequent sub-templates. You can use the tag{% extends %} cap (a poem){% block %} to implement inheritance.

The use case for this is simple: as your application grows, and as you continue to add new templates, you will need to keep public code (such as HTML navigation bars, Javascript libraries, CSS stylesheets, etc.) in sync, which can require a lot of work. Using inheritance, we can move these public parts to the parent/base template so that we can create or edit such code once and all child templates will inherit that code.

Note: You should always add as much duplicate code to the base template as possible to save time in the future, which will far outweigh the initial time investment.

Let's add templates to our DEMO:

1) Create a base template (save as

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/bootstrap/3.0.0/css/" rel="stylesheet" media="screen">
    <style type="text/css">
      .container {
        max-width: 500px;
        padding-top: 100px;
      }
      h2 {color: red;}
    </style>
  </head>
  <body>
    <div class="container">
      <h2>This is part of my base template</h2>
      <br>
      {% block content %}{% endblock %}
      <br>
      <h2>This is part of my base template</h2>
    </div>
    <script src="/jquery-1.10."></script>
    <script src="/bootstrap/3.0.0/js/"></script>
  </body>
</html>

You noticed.{%block%} Marked? This defines the blocks or areas that the sub-template can fill. In addition, overrides can also be implemented.

2) Update with a template :

{% extends "" %}
{% block content %}
  <h3> This is the start of my child template</h3>
  <br>
  <p>My string: {{my_string}}</p>
  <p>Value from the list: {{my_list[3]}}</p>
  <p>Loop through the list:</p>
  <ul>
    {% for n in my_list %}
    <li>{{n}}</li>
    {% endfor %}
  </ul>
  <h3> This is the end of my child template</h3>
{% endblock %}

this kind of The content block in the template is then The final result is as follows:

Then, we can modify the Add a generic navigation bar to it now: (insert the following code into the (used form a nominal expression)<body> (after the label)

<nav class="navbar navbar-inverse" role="navigation">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">Jinja!</a>
    </div>

    <div class="collapse navbar-collapse" >
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
      </ul>
      <form class="navbar-form navbar-left" role="search">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li class="divider"></li>
            <li><a href="#">Separated link</a></li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

Now, every sub-template that extends from the base will have the same navigation bar. To borrow a phrase from Java philosophy, "Write once, use anywhere."

4、Super Blocks

If you need to render the block from the base template, use super block:

{{ super() }}

Add a footer to the base template:

<body>
<div class="container">
 ...
  <h2>This is part of my base template</h2>
  <br>
  <div class="footer">
    {% block footer %}
      Watch! This will be added to my base and child templates using the super powerful super block!
      <br>
      <br>
      <br>
    {% endblock %}
  </div>
</div>
...

At this point, we can give the Add super block so that the child template reuses the blocks in the parent template:

{% extends "" %}
{% block content %}
  <h3> This is the start of my child template</h3>
  <br>
  <p>My string: {{my_string}}</p>
  <p>Value from the list: {{my_list[3]}}</p>
  <p>Loop through the list:</p>
  <ul>
    {% for n in my_list %}
    <li>{{n}}</li>
    {% endfor %}
  </ul>
  <h3> This is the end of my child template</h3>
  {% block footer %}
  {{super()}}
  {% endblock %}
{% endblock %}

The effect is as follows:

super block is used when a module shares the block of its parent module, but of course there are some advanced ways to play with it, such as the following example:

Parent template:

{% block heading %}
  <h1>{% block page %}{% endblock %} - Flask Super Example</h1>
{% endblock %}

Subtemplates:

{% block page %}Home{% endblock %}
{% block heading %}
  {{ super() }}
{% endblock %}

This way when the submodule is accessed, it will splice a<h1>Home - Flask Super Example</h1> Fields. Notice that, by doing this, we realize the inheritance of the title (with some inheritance and some information about the submodule itself).

Back on track, for the update title, we designed it like this here (modified) (two lines of code in the)

{% block title %}{{title}}{% endblock %}
...
{% block page %}{{title}}{% endblock %}

This way we can come in via python and change the title directly (modify the):

@("/")
def template_test():
    return render_template(
        '', my_string="Wheeeee!", 
        my_list=[0,1,2,3,4,5], title="Home")

5、Macros

In Jinja, we can use macros to abstract commonly used code snippets that are reused over and over again to avoid repetition. For example, it is common to highlight a link to the current page (the active link) on the navigation bar. Otherwise, we would have to use if/elif/else statements to identify the active link. Using macros, we can abstract this code into a single file.

Add a Documentation:

{% macro nav_link(endpoint, name) %}
{% if (endpoint) %}
  <li class="active"><a href="{{ url_for(endpoint) }}">{{name}}</a></li>
{% else %}
  <li><a href="{{ url_for(endpoint) }}">{{name}}</a></li>
{% endif %}
{% endmacro %}

Here, we use Flask's request object (a default part of Jinja) to check the request endpoint and then assign the active class to that endpoint.

Update the unordered list using the nav navbar nav class in the base template:

<ul class="nav navbar-nav">
  {{ nav_link('home', 'Home') }}
  {{ nav_link('about', 'About') }}
  {{ nav_link('contact', 'Contact Us') }}
</ul>

Also, make sure to add the import at the top of the template:{% from "" import nav_link with context %}

Finally, let's add three new endpoints to the controller:

@("/home")
def home():
    return render_template(
        '', my_string="Wheeeee!", 
        my_list=[0,1,2,3,4,5], title="Home")

@("/about")
def about():
    return render_template(
        '', my_string="Wheeeee!", 
        my_list=[0,1,2,3,4,5], title="About")

@("/contact")
def contact():
    return render_template(
        '', my_string="Wheeeee!", 
        my_list=[0,1,2,3,4,5], title="Contact Us")

Refresh the page. Test the links at the top. Is the current page highlighted? (Every time you click Home, About, Contact Us, the browser automatically jumps to the corresponding url and loads the page)

6、Customized filter

Jinja uses filters to modify variables, mainly for formatting purposes.

Here's an example;

{{ num | round }}

This will round the num variable. So if we pass the parameter num=46.99 into the template, it will output 47.0. (Think of the statement in curly braces as a shell, and you'll see that the vertical line is the pass-through action, and the round is a filter, and here are all the(machine) filter)

One more example:

{{ list|join(', ') }}

You can add a comma to the variables in the list array.

In fact, in addition to the self-contained filters, we can also customize them:

1) Add before all functions ofapp = Flask(__name__) Used to create an app
2) Add a datetimefilter function and register it with the app's filter

@app.template_filter() # For the record, it's a filter #
def datetimefilter(value, format='%Y/%m/%d %H:%M'):
    """Convert a datetime to a different format."""
    return (format)

app.jinja_env.filters['datetimefilter'] = datetimefilter

3) In this way, we insert the following code in the sub-template:

<h4>Current date/time: {{ current_time | datetimefilter }}</h4>

4) Finally, just pass the time into the template in python:

current_time = ()

5) The effect is as follows:

7. Conclusion

In this way, we send you a quick start Jinja, the source code:/mjhea0/thinkful-mentor/tree/master/python/jinja/flask_example

Reference Links

[1]. Source code for this article
[2]. Primer on Jinja Templating (Translation of this article and reference to this one)
[3]. Flask Official Documentation
[4]. Really figuring out the difference between Django and Flask frameworks in Python
[5]. Flask Home
[6]. A Soft UI Dashboard - Free Jinja Template
[7]. Appseed is a site with many Flask templates!
[8]. Nginx Server SSL Certificate Installation and Deployment
[9]. python django web development -- 15 minutes to get it working (that's as far as I can send you)

to this article on python flask framework Jinja template Getting Started article is introduced to this, more related python flask Jinja template content, please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!