Django template system: Template

First, the common template syntax

1.1 Variable

  1. Symbols: {} {}
    • Represent variables, replace the value in the template when rendering
    • Use: {{}} variable name: alphanumeric variable name and underscores
    • Dot (.) Has a special meaning in the template language, corresponding to the acquired attribute of the object
    • Note: (.) ​​When the system encounters a template, we will go to the query in the following order:
      • Query in the dictionary
      • Property or method
      • Digital Index

1.2 Built-in filter

  1. filter: shows the results of the filter, to change the variable

    • Syntax: {{value | filter_name: parameters}}
    • ':' There is no space left and right is no space without a space
  2. Built-in filter

    • default: default value

      • 语法:{{ value|default:"nothing"}}
      • If the value is not passed, then the value will show nothing
      • Supplementary: TEMPLATES The OPTIONS can add an option: string_if_invalid: 'find', can replace the role of the default
    • filesizeformat: file size, the value of a readable format file size

      • 语法:{{ value|filesizeformat }}
      • Such as, value = 123456789, the output will be 117.7 MB
    • add: add parameters to a variable

      • Syntax: {{first | add: second}}
      • Priority to see if the sum into digital, followed by the string concatenation
      • If the list is equivalent to extend, join cycle
    • length: Returns the length

      • Syntax: {{value | length}}
      • Returns the value of the length, such as, value = [ 'a', 'b', 'c', 'd'], then it displays 4
    • slice: Slice

      • Syntax: {{value | slice: "2: -1"}}
    • first / last: take the first / last element

      • grammar:
        • Take the first element: {{value | first}}
        • Take the last element: {{value | last}}
    • join: using string concatenation list

      • 语法:{{ value|join:" // " }}
    • truncatechars: cut, according to the character count

      • truncatewords: alphabetically count does not recognize Chinese
      • If the string of characters is more than a specified number of characters, it is truncated
      • Ends with an ellipsis sequence truncated strings will be translated (...)
      • Parameters: truncated character
      • Syntax: {{value | truncatechars: 9}}
    • date: Date Format

      • 语法:{{ value|date:"Y-m-d H:i:s"}}

      • In settings.py is configured:

        USE_L10N = False
        
        DATETIME_FORMAT = 'Y-m-d H:i:s'    # datetime类型
        DATE_FORMAT = 'Y-m-d'            # date类型
        TIME_FORMAT = 'H:i:s'            # time类型
      • After configuration, using {{now}} may be implemented formatted date

        • 其中,'now':datetime.datetime.now()
    • safe: tell django code is secure, no escape

      • Syntax: {{value | safe}}
      • Such as,value = "<a href='#'>点我</a>"

1.3 Custom filter

  1. Create a python package called templatetags in app

  2. Py file created in templatetags, the file name of the custom (my_tags.py);

  3. In the py file write:

    from django import template
    register = template.Library()        # register也不能变
  4. + Write a function decorator

    @register.filter
    def add_xx(value, arg):          # 最多有两个
        return '{}-{}'.format(value, arg)
    
    @register.filter(name='adds')    # 相当于更改了函数名,使用时,使用新的函数名
  5. Use in the template file, html file

    {% load my_tags %}
    {{ 'alex'|add_xx:'dsb' }}
  6. note:

    • To avoid errors, templatetags best is a Python package, and the name can not be changed
    • register name can not change the need to restart the project, if necessary
    • init in Python package may have other content django does not recognize, result in an error, you can delete content directly

1.4 Label tag

  1. Symbol:%%} {

  2. for loop

    <ul>
    {% for user in user_list %}
        <li>{{ user.name }}</li>
    {% endfor %}
    </ul>
    • forloop: a dictionary
    Variable Description
    forloop.counter Loop current index value (starting at 1)
    forloop.counter0 Loop current index value (zero)
    forloop.revcounter Reverse current loop index (1 to end)
    forloop.revcounter0 Reverse circulating current index value (0 to end)
    forloop.first The current cycle is not the first cycle (Boolean value)
    forloop.last The current cycle is not the last cycle (Boolean value)
    forloop.parentloop This layer of outer loop cycles
    • for ... empty
    {% for book in all_books %}
        <tr>
         .....
        </tr>
    {% empty %}
        <td>没有相关的数据</td>
    {% endfor %}
  3. if the judge

    • if statement supports and, or, ==,>, <,! =, <=,> =, in, not in, is, is not judged
    {% if 条件1  %}
     xxx
    {% elif 条件2  %}
        xxx
    {% else  %}
     xxxxx
    {% endif %}
    • Continuous judge
      • python中,10>5>1 --> 10>5 and 5>1 --> true
      • js中,10>5>1 --> true>1 --> 1>1 --> false
      • Template, not supported on continuous determination does not support an arithmetic operation (filter can be used)
  4. with: to rename the variable, but only with the entry into force in the region

    {% with hobby.2 as talk %}
    {# 相当于 {% with talk=hobby.2 %},其中=两边不能有空格 #}
     {{ talk }}
    {% endwith %}
  5. csrf_token

    • The label for protection CSRF
      • csrf: CSRF
    • Use: in the form written on a form {% csrf_token%}
    • So do not comment middleware with csrf of the settings in the

1.5 Notes

  • Symbols: {# #} content to be annotated

  • Shortcut: Ctrl +?

    {# 要注释的内容 #}

Second, the motherboard and inheritance

2.1 Motherboard

  1. Motherboard is an ordinary html, extracting a plurality of pages of the public portion of the definition is achieved by block block

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="x-ua-compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Title</title>
        {% block page-css %}
    
        {% endblock %}
    </head>
    <body>
        <h1>这是母板的标题</h1>
        {% block page-main %}
    
        {% endblock %}
        <h1>母板底部内容</h1>
        {% block page-js %}
    
        {% endblock %}
    </body>
    </html>
  2. block block:

    {% block 块名 %}
    
    {% endblock %}
  3. Note: We usually define the page dedicated block in the motherboard CSS and JS block to facilitate sub-page replacement

2.2 Inheritance

  1. Motherboard subpages Inheritance: {% extends 'master html'%}

    {% extends 'layouts.html' %}
  2. Subpages block block by rewriting to replace the mother board corresponding content

    {% block page-main %}
        <p>世情薄</p>
        <p>人情恶</p>
        <p>雨送黄昏花易落</p>
    {% endblock %}

2.3 Note

  1. {% Extends 'base.html'%} write the first line, in front do not have content or contents show
  2. {% Extends 'base.html'%} of 'base.html' must be quoted, or will be treated as a variable to find
  3. The sub-page content to be displayed in the block write block, it would not show up
  4. Location plurality of unique content, can define a plurality of block block, special: define css, js blocks, etc.

Third, the components

  1. Components: a short snippet html

  2. As conventional navigation page content, footer information components may be stored in a separate file, and then introduced into use where necessary

    {% include 'navbar.html' %}

Fourth, the static files related

  1. Objective: To change the setting in the alias static files, before you change does not affect static file reference, that reference will automatically change to follow the change aliases, thus not being given the

  2. Method One: Use the static, the original path: /static/images/hi.jpg

    {% load static %}
    <img src="{% static "images/hi.jpg" %}" alt="Hi">
    • Many files can be saved to be used as a variable
    {% load static %}
    {% static "images/hi.jpg" as myphoto %}
    <img src="{{ myphoto }}">
  3. Method Two: Use get_static_prefix, the original path: /static/images/hi.jpg

    {% load static %}
    <img src="{% get_static_prefix %}images/hi.jpg" alt="Hi">
    
    {# 补充:获取别名 #}
    {% get_static_prefix %}
    • Many files can be saved to be used as a variable
    {% load static %}
    {% get_static_prefix as STATIC_PREFIX %}
    <img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi">

Fifth, custom simple_tag

  1. Custom filter and the like, the difference between: the received parameter is more flexible, capable of receiving the universal parameter

  2. Registration is defined simple_tag

    @register.simple_tag
    def join_str(*args, **kwargs):
        return '{} - {} '.format('*'.join(args), '$'.join(kwargs.values()))
    
    @register.simple_tag(name='join')    # 相当于更改了函数名,使用时,使用新的函数名
  3. Use custom simple_tag

    {% load my_tags %}
    {% join_str '1' '2' k1='3' k2='4' %}

六、inclusion_tag

  1. templatetags (python package) at app creation py file, the file name of the custom (my_inclusion.py);

  2. In the py file write:

    from django import template
    register = template.Library()        # register也不能变
  3. + Write a function decorator

    @register.inclusion_tag('result.html')
    # result.html 是内容的html
    def show_results(n):
        n = 1 if n < 1 else int(n)
        data = ["第{}项".format(i) for i in range(1, n+1)]
        return {"data": data}
  4. In result.html wrote:

    <ul>
        {% for choice in data %}
        <li>{{ choice }}</li>
        {% endfor %}
    </ul>
  5. Use the template file

    {% load my_inclusion %}
    {% show_results 10 %}

Guess you like

Origin www.cnblogs.com/zengyi1995/p/11079537.html