Python's Flask framework Standard template engine JINJA2 use tutorial

Source: Internet
Author: User
JINJA2 requires more than Python2.4 version.
Installation
There are several ways to follow Jinja, and you can choose different ways to do it according to your needs.
Use Easy_install or PIP:

These two tools can be automatically downloaded from the Web site Jinja, and installed in the Python directory of the Site-packages directory.
To install from the TAR package:

Basic API Usage
The simplest way to create a template with Jinja is through template. However, this usage is not recommended in practical applications:

  >>> from Jinja2 import Template  >>> template = Template (' Hello {{name}}! ')  >>> Template.render (name= ' world ')  

This example creates a template instance using a string as a templated content, and then invokes the Render method with "Name= '" as a parameter, substituting ' name ' in the content with "world", and finally returning the rendered string-"U ' Hello World! ' ".
There are two types of separators. {% RAW%} {% ... %} {% Endraw%} and {% raw%}{{...}} {% Endraw%}. The first is used to perform a declaration like a for loop or assignment, which is used to output the result of the expression into the template.

How to Organize templates
So how does the template fit into our app? If you have been concerned about Flask, you may have noticed that Flask is very flexible and does not impose some special restrictions on its content. Templates are no exception. You may also notice that there is usually a recommended place to put things (for example, templates). For a template, that place is in the package directory.

myapp/  __init__.py  models.py  views/  templates/  static/run.pyrequirements.txttemplates/  layout.html  index.html  about.html  profile/    layout.html    index.html  photos.html  admin/    layout.html    index.html    analytics.html

The structure of the templates directory is parallel to our routing structure. The template for routing myapp.com/admin/analytics is templates/admin/analytics.html. There are additional templates in the directory that are not directly rendered. The layout.html file is intended for other templates to inherit.

Inherited
Much like Batman's background story, an organization's excellent template catalog relies heavily on inheritance. A parent template typically defines a common structure that all child templates can inherit well. In our case, layout.html is a parent template and the other. html files are child templates.
You usually have a top-level layout.html that defines the general layout of your application and every part of your site. If you look at the list above, you'll see a top-level myapp/templates/layout.html, as well as myapp/templates/profile/layout.html and myapp/templates/. Admin/layout.html. The last two files inherit and modify the first file.

{# _myapp/templates/layout.html_ #}      {% RAW%} {% block title%} {% Endblock%} {% Endraw%}      {% block body%}    

This heading was defined in the parent.

{% Endblock%}

In the child template, we can extend the parent template and define the contents of those blocks.

{# _myapp/templates/index.html_ #} {% extends "layout.html"%} {% block title%} Hello world! {% Endblock%} {% block body%}  {{super ()}}  

This heading was defined in the child.

{% Endblock%}

The super () function lets us render the contents of a parent block.

Create a macro
We can stick to the principle of DRY (do not repeat ourselves) in our template by abstracting the repeated occurrences of the code snippet to the macro. If we are working on HTML for our application navigation, we need to give an "active" link to a Class (class= "active"). Without a macro, we're going to write a big if ... else statement that checks each link to find the one that is active.
Macros provide a way to modularize code; they work like functions. Let's see how to use a macro to mark an active link.

{# myapp/templates/layout.html #} {% from ' macros.html ' import nav_link with context%}    {% block head%}    My Application  {% Endblock%}        
 { 
  
  
    {nav_link (' home ', ' Home ')}} {{Nav_link (' about ', ' on ')}} {{nav_link (' contact ', ' Get in Touch ')} }
{% block body%} {% endblock%}

What we're going to do now in this template is to call an undefined macro-nav_link-and then pass two parameters to it: the target endpoint (for example, the function name of the target view) and the text we want to display.
You may notice that in the import statement we specify the with context. The context of Jinja is made up of the arguments passed to the render_template () function and the Jinja environment contexts from our Python code. For templates, these variables are available when the template is rendered.
Some variables are obviously passed by us, for example, Render_template ("index.html", color= "Red"), but there are also variables and functions that are automatically included in the context by Flask, for example, request, G, and session. When we say {% raw%}{% from ... import ... with context%}{% endraw%}, it is telling Jinja that these variables are also available to macros.
Now it's time to define the Nav_link macros used in our templates.

{# myapp/templates/macros.html #} {% macro Nav_link (endpoint, text)%} {% if Request.endpoint.endswith (endpoint)%}  
  • {{text}}
  • {% Else%}
  • {{text}}
  • {% ENDIF%} {% ENDMACRO%}

    Now we have defined the macros in myapp/templates/macros.html. In this macro we use the Flask request Object-which is available by default in the Jinja context-to check whether the endpoint passed into the route in Nav_link is the current request. If yes, we are on the current page, and then we mark it as active.
    The Y statement imported from x takes the relative path of x. If our template is myapp/templates/user/blog.html, we can use the from ". /macros.html "Import Nav_link.

    Custom Filters
    The Jinja filter is a function that can be in {% raw%}{{...}} {% Endraw%} is used to process the result of an expression. It is called before the expression results are output to the template.

    {{Article.title|title}}

    In this code, the title filter receives Article.title as a parameter and returns a filtered caption, and the filtered caption is then output to the template. This is like the UNIX "plumbing" one program to the output of another program.
    There are many built-in filters like title. See the full list in the Jinja documentation.
    We can define our own filters for use in our Jinja templates. For example, we will implement a simple caps filter to capitalize all the letters in a string.
    Jinja already has a upper filter to do such things, and there is also a capitalize filter that can be used to capitalize the first letter and the rest of the lowercase letters. These can also handle Unicode conversions, but we will continue our example so that you can now know how to customize the filter.
    We're going to define our filters in myapp/util/filters.py. Here is a util package, which has a variety of modules.

    # Myapp/util/filters.pyfrom. Import App@app.template_filter () def caps (text): "" "  Convert a string to all caps.  " " Return Text.uppercase ()

    In this code we use the @app. Template_filter () Adorner registers our function as a jinja filter. The default filter name is the name of the function, but you can pass in a parameter to the adorner to change it.

    @app. Template_filter (' make_caps ') def caps (text): "" "  Convert a string to all caps.  " " Return Text.uppercase ()

    Now we can call make_caps instead of {% raw%}caps:{{"Hello world!" in the template | Make_caps}}{% endraw%}.
    In order for our filter to be available in the template, we only need to import it in our top-level \\_init.py\\_.

    # myapp/__init__.py# Make sure app have been initialized first to prevent circular imports.from. Util Import Filters
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.