Flask template jinja2

  1. Template warm-up

    • When rendering a template, the default template will look from the 'templates' directory under the project root directory.

    • If you do not want to put the template file 'templates' directory, you can specify the path 'template_folder' template to specify at the time of 'Flask' initialization

  2. Pass module parameters

    • 1. Use 'render_template' renders the template, they can pass keyword arguments. Later can be used directly in the template

    • 2. If you have too many parameters, you can put all the parameters into a dictionary, and the dictionary parameter re-transmission when using two asterisks, to break into the keyword arguments dictionary

    • 3. If you want to re-visit the HTML parameter we pass such transfer is username = 'xiaoxin'

      • If the keyword is a parameter directly {{username}}, we can map the parameter corresponding to the front page content

      • If passed, such as the dictionary

        • content = { 'name': 'age'} then {{content.name}} may be able to be mapped onto the inside of the front end of age

        • ** content using the dictionary corresponding to the parameters, parameter passing into the keyword, and then directly {{username}}, we map the content parameters to the front page

  3. Used in the template url_for

    • Template url_for use with our backstage view of the function of url_for it is basically exactly the same, but also passing the name of the view function, you can pass parameters

    • When used inside the html then, both sides need to add urlfor {{url_for ( 'func')}}

  4. The basic use of filters

    • Sometimes we want to re-template to deal with a number of variables, then we must need similar function as Python is, this value can be passed to the function, and then do something

    • The basic syntax:

      • {{Variable | filter name}}. Pipe symbol '|' combined

    • Filter through a pipe symbol | of use, such as column {{name | length}} (), returns the name length. It is equivalent to a filter function, the current passed to the variable filter, and the filter according to their functions, and then returns the corresponding value, then after rendering result into the page. Jinja2 built a lot of filters, then here you can see all of the filters, now for some commonly used filters breakdown:

      • abs (value): Returns the number of columns as the absolute value of a -1 | abs

      • default (value, default_value, boolean = false): If there is no current variable value e, the value of the parameter will be used instead. {{Name | defaule ( 'xiaotuo')}} - If the name does not exist, instead of using .boolean default xiaotuo = False, then only this variable will be used in undefined time in the default values, if you want to use python is determined whether the form is false (such as columns: None, an empty string, an empty list, empty dictionary, etc.), can be passed boolean = true

        • Or may be used instead of default ( 'Default', boolean = True). E.g.

          • {{Singature or 'who is lazy, did not leave a description'}}

      • Automatically escaped Filters:

        • escape (value) or e:. escape character will <> characters escaped to the symbols in the HTML. The columns: content | escape or content | e

        • safe (value): If you turn the global escaped, then safe to turn off the filter variable will escape. Example: content_html | safe

        • autoescape tag, or can be turned off automatically escaped inside his code block

          • {% Autoescape off / on%} off is automatically closed on the escape opening is automatically escaped

          • ..... block

          • {%endautoescape%}

      • first (value): returns a sequence of the first element. names | first

      • format (value, * args, ** kwargs): format string. E.g

        • {{"%s-%s"|format('hello?',"Foo!”)}} 将输出: hello?-Foo!

      • last (value): Returns the last element of a sequence. Examples of names | last

      • length (value): returns the length of a sequence or dictionary. Examples of names | length

      • join (value, d = u "): the value of d using a splicing sequence of this parameter to a string

      • int (value): value converted to type int

      • float (value): value converted to float

      • lower (value): string to lowercase

      • upper (value): converts a string to upper case

      • replace (value, old, new): new replace the old string

      • truncate (value, length = 255, killwords = False): the length of the interception of the string length

      • striptags (value): deletes all HTML tags in the string, if the occurrence of multiple spaces will be replaced with a space

      • trim: blank character string taken of the front and rear

      • string (value): converts a string variable

      • wordcount (s): calculating the number of a long string of words

    • Custom template filters

      • The filter is essentially a function, if you call this filter in the template, it will be the value of this variable as the first argument passed to the filter function, and then return value as the filter function's return value . It requires the use of a decorator @ app.template_filter ( 'cut')

      • 1. In the python file, write your own filters.

        • @ App.template_filter ( 'cut') # decorator inside pass filter our custom names for easy re-use HTML

        • def cut (value): value again when the html call when the custom filter, will call the custom filter variable value passed

          • value = value.replace('hello','')

          • return value

      • 2. In HTML

        • < p>{{story|cut}} < /p>

  5. Detailed control statements

    • All control statements are placed .... {%}%, and there is a statement {%}% EndXXX end .Jinja2 commonly used to control statements have if / for .... in ..., now explain to them

      • 1.'if ': if the python and similar statements can be used>, <, <=,> =, ==, = to be judged, can also!' And or not, () 'to perform the logical merge operations, see the following Liezi

        • + {% if kenny.sick %}
            + kenny is sick.
          + {% elif kenny.dead %}
            + You killed Kenny! You bastard!!!
          + {%else%}
            + Kenny looks okay---so far
          + {%endif%}
      • 2.'for .... in ... ':' for 'loop can iterate a sequence including any array, dictionary, tuples. And can reverse traversal. The following will be explained by several Liezi:

        • Normal traversal

          • + < ul>
            + {%for user in usres%}
            + < li>{{user.username|e}} < /li>
            + {%endfor%}
            + < /ul>
        • Traversing the dictionary:

          • + < dl>
            + {%for key,value in my_dice.iteritems() %}
            + < dt> {{key|e}}</ dt>
            + < dd> {{value|e}}< /dd>
            + {{%endfor%}}
            + < /dl>
        • If the sequence is not the time value into the 'else'

          • + < ul>
            + {%for user in usres%}
            + < li>{{user.username|e}} < /li>
            + {%else%}
            + < li>< em>no users found< /em>< /li>
            + {%endfor%}
            + < /ul>
        • Jinja for loop and further comprising the following variables can be used to obtain the current traversal state:

          • Variable Description

          • loop.index current iteration index (starting with 1)

          • loop.index0 current iteration index (starting from 0)

          • Whether loop.first is the first iteration, returns Ture or False

          • loop.last whether it is the last iteration, returns True or False

          • Sequence length loop.length

        • Further, the expression can not be used to break and continue execution of the control cycle

  6. The use of macros

    • The basic concept of macro and use

      • Template with a macro similar to the python function, the transfer function can be, but does not return a value, some of the frequently used code fragments may be placed in a macro, and some fixed value is not extracted, as to a variable, when using macros, parameters can be default values. The following will be explained with a Liezi:

        • Macro definitions

          • + {%macro input(name,value="",type='text')%}
              + < input type="{{type}}",name="{{name}}",value="{{value|e}}">
            + {%endmacro%}
      • Liezi can be pulled out more than a label input to specify some default parameters. So we created 'input' tag later time, you can quickly create through her

        • Use macros

          • + < p>{{input('usename') }}< /p>
            + < p>{{input('password',type='password')  }} < /p>
    • The import statement

      • In a real development, it will be some of the commonly used macros in a single file, when you need to use, and import from this file. 'Import' usage statement with 'python' in the 'import' Similarly, you can directly 'import .... as ....', can also be from .... import .... or from .... import .... as ..., suppose we have a file called forms.html, there are two macros are input and textarea below

        • + {%macro input(name,value="",type='text')%}
            - < input type="{{type}}",name="{{name}}",value="{{value|e}}">
          + {%endmacro%}
          + {%macro textarea(name,value="",rows=10,cols=40)%}
            - < textarea name="{{name}}"  rows="{{rows}}" cols="{{cols}}">{{value|e}} < /textarea>
          + {%endmacro%}
      • Import macros Liezi

        • Macro file path, not a relative path to find, have to 'templates' to find as an absolute path

        • If you want the import of the macro, put the current number of parameters passed to the macro templates where the template, then it should be used with context at the time of import example

          • from 'xxx.html' import input with context

        • + 1.import....as....形式:
            + {%import 'forms.html' as forms%}
            + < dl>
              + < dt>Username< /dt>
              + < dd>{{forms.input('username') }} < /dd>
              + < dt>Password< /dt>
              + < dd>{{forms.input('password',type='password') }} < /dd>
            + < /dl>
            + < p> {{forms.textarea('comment') }} < /p>
          + 2.from...import....as..../from....import...形式
            + {%from 'forms.html' import  input as input_field,textarea %}
    • include tag

      • This tag is equivalent to simply copy and paste the template code assigned to the current location

      • 'Include' label, if you want to use the parent variables in the template, can be used directly, you do not need to use with context

      • Path include, as well as with import, went directly from the 'templates' root directory, do not go to a relative path

        • {% Include 'pathname .html'%}

    • set and with statements and variables defined in the template

      • set statement:

        • In the template, you may be used 'set' statements to define the variables, the following example

          • {% Set username = 'small Xin'}%

          • Once you define this variable, then later in the code, you can use this variable, similar to the definition of the variables is the same python

      • with the statement:

        • with statement variables can only be used in the 'with' statement block, this block over, it can not be used again. The following exemplary code blocks

          • + {%with classroom='xiaoxin1'%}
            + < p> 班级: {{classroom}} < /p>
            + {%endwith%}
        • with statement does not necessarily keep a variable can be defined an empty 'with' statement later 'with' blocks 'set' defined variables, then this can only 'with' used in the block

          • + {%with %}
            + {%set classroom='xiaoxin1'%}
            + < p> 班级: {{classroom}} < /p>
            + {%endwith%}
    • Load static files (images, CSS, JS)

      • 1. Load Static files url_for function is used, then the first parameter required for the 'static', the second parameter is a required keyword parameter 'filename = "Path" "Example:

        • {{url_for("static",filename="xxx") }}

      • Pathfinder, to be 'static' directory as the root directory of the current project

    • Detailed template inheritance

      • Why do we need template inheritance

        • Template Inheritance some common code can be extracted out into a single parent template, after the sub-templates can be used directly inherited, and thus reducing repetitive code, and also more convenient since modifications

      • Template inheritance syntax:

        • Use 'extends key phrases', to indicate inherit the parent template. Path parent template, but also with respect to the templates folder the absolute path. The following sample code

          • {%extends 'base.html'%}

      • block syntax:

        • Generally in the parent template, you can only define some common code. The child may have to implement different template code based on specific needs. This time the parent template should have the ability to provide an interface that allows the child to achieve a template to perform the functions specific business needs.

        • In the parent template

          • {% block block name% }
             {%}% endblock
        • In sub-template method is also called rewriting (override the parent template inside the block)

          • + {% Block block name% }
             + sub-template code
             + {% endblock%}
      • Calling Parent template code blcok code

        • By default, the father of the child to achieve a template if the template definition block, then the sub-template block code in the code will overwrite the parent template. If you want to still keep the code the parent template in the sub-template, you can use {{super ()}} to achieve. Examples are as follows

          • Parent template

            • + {% Block block name% }
               + which is inside the parent template code
               + {% endblock%}
          • Sub-template

            • + {% Block block name% }
               + {{Super ()}}
               + which is a sub-template code
               + {% endblock%}
      • Another source calls a block of

        • If you want to use another code template other templates, then by {{self. Other block name ()}} the following sample code can

          • %% Block title {+ }
             + What is Home
             + {% endblock% }
             +
            % Block body_block% {+ }
             + {{self.title ()}}
             + I sub-template code
             + {% endblock%}
      • Other Considerations

        • 1. The sub-code templates, the first line, it should be 'extends'

        • 2. The sub-template, if you want to implement your own code should be placed in the block, if placed elsewhere, then it will not be rendered

Guess you like

Origin www.cnblogs.com/fengzi759/p/12152446.html