The Python flask Framework is standard with the template engine Jinja2 tutorial _python

Source: Internet
Author: User

JINJA2 need to Python2.4 the above version.
Installation
According to Jinja there are many ways in which you can choose different ways to follow.
Use Easy_install or PIP:

#sudo easy_install Jinja2 
#sudo pip install Jinja2 

These two tools can automatically download Jinja from a Web site and install it into the site-packages directory of the Python directory.
Install from tar pack:
# Download Jinja installation package 
# unzip 
# sudo python setup.py install 

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

<pre> 
 >>> from Jinja2 import Template 
 >>> Template = Template (' Hello {{name}}! ') 
 >>> Template.render (name= ' World ') 
 u ' Hello world! ' 
</pre> 

This example creates a template instance using a string as the template content, and then calls the Render method with "Name= '" as a parameter, replacing ' name ' in the content with ' world ', and finally returning the rendered string--"U" Hello World! ' ".
There are two types of separator characters. {% RAW%} {% ... %} {% Endraw%} and {% raw%}{{...}} {% Endraw%}. The first is to execute a declaration that resembles 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 a template fit into our application? If you've been paying attention to flask, you may have noticed that flask is very flexible and has no specific limitations 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.py requirements.txt
templates/
  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 to allow other templates to inherit.

Inherited
like Batman's background story, an organization's excellent template catalogs depend heavily on inheritance. The parent template usually defines a generic structure, and all of the child templates inherit it well. In our example, layout.html is a parent template and the other. html file is a child template.
You usually have a top-level layout.html that defines the general layout of your application as well as every part of your site. If you look at the above catalogue, you will see a top floor 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_ #}
<! DOCTYPE html>
 
 

In a 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 ()}}
   
 

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

Creating macros
we can stick to the principle of DRY (don't repeat ourselves) in our template by abstracting the repeated snippets of code into the macros. If we are working on the HTML for our application navigation, we need to give an "active" link to one Class (class= "active"). Without macros, we're going to write a large 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 Macros to mark an active link.

 {# myapp/templates/layout.html #} {% from ' macros.html ' import nav_link with context%} <!
  DOCTYPE html>  
 

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

{# myapp/templates/macros.html #}
{% macro Nav_link (endpoint, text)%}
{% if Request.endpoint.endswith (endpoint)%}
  <li class= "Active" ><a href= "{url_for (Endpoint)}}" >{{text}}</a></li>
{% Else%}
  <li><a href= ' {url_for (endpoint)}} ' >{{text}}</a></li> {% endif%}
{% Endmacro%}

Now we have defined 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 of the route passed in to Nav_link is the current request. If so, we are on the current page and then we mark it as active.
Importing the Y statement 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%}{{...}} The result of processing an expression in {% Endraw%}. It is invoked before the result of the expression is exported to the template.

 
 

In this code, the title filter receives Article.title as a parameter and returns a filtered caption, and the filtered title is then exported to the template. This is like the UNIX "pipelining" one program to another program's output.
There are a lot of built-in filters like title. See the complete list in the Jinja documentation.
We can define our own filters for use in our Jinja template. 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 a thing, and there is also a capitalize filter that can be used to capitalize the first letter, lowercase the rest of the letters. These can also handle Unicode conversions, but we will continue with our example so that you can now know how to customize the filter.
We're going to define our filters in the myapp/util/filters.py. Here is a util package, which has a variety of modules.

# myapp/util/filters.py from
. 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 to register our function into 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 in the template instead of {% raw%}caps:{{"Hello world!" | Make_caps}}{% endraw%}.
In order for our filters to be available in the template, we only need to import it in our top-level \\_init.py\\_.

# myapp/__init__.py
# Make sure app has been initialized the prevent to circular imports.
From. Util Import Filters

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.