Djang template system

Django template system

Common Syntax: {{}} and {%}%

Related variables {} {}, the logic associated with {%}%.

variable:

Click Django template language syntax used in: {{name}} variable. When the template engine encounters a variable, it will calculate the variable, and then replace it with the result itself.

Dot (.) Has a special meaning in the template language. When the template system encounters a dot ( "."), It will look in this order:

  1. Dictionary lookup (Dictionary lookup)
  2. Property or method query (Attribute or method lookup)
  3. Digital index query (Numeric index Lookup)

Precautions:

  1. If the value of calculation result is called, it will be invoked with no parameters. Result of the call will be the value of the template.
  2. If the variable does not exist using the template system inserts string_if_invalid option value, which is set to default: '' (the empty string)

A few examples:

# view.py

def test(request):
    list_1 = [1, 2, 3]
    dict_1 = {'name': 'goudan'}
    
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
            
        def sb(self, name):
            return f'{name} is sb'
        
    
    Zhangsan = Person(name='Zhangsan', age=13)
    Lisi = Person(name='Lisi', age=14)
    person_list = [Zhangsan, Lisi]
    
    return render(request, 'text.html', locals())

Template support wording:

# text.html

{# 取l中的第一个参数 #}
{{ list_1.0 }}
{# 取字典key的值 #}
{{ dict_1.name }}
{# 取对象的name属性 #}
{{ person_list.0.name }}
{# .操作只能调用不带参数的方法 #}
{{ person_list.0.sb }}

1, Filters (filter)

In Django template language by using filters to change the display of variables. The syntax of the filter: {{value | filter_name:}} parameters. Use pipe symbol "|" applying a filter.

For example: {{name | lower}} then the variable name will show its value after the application of lower filter. lower then the role of the text here is all lowercase.

Precautions:
  1. Filter supports the "chain" operation. I.e., a filter output as input to another filter.
  2. Filters can accept parameters, for example: {{sss | truncatewords: 30}}, which will display the first 30 words of sss.
  3. Filter parameter contains a space, it must be wrapped in quotes such as comma and a space used to connect the elements of a list, such as:. {{List | join: ','}}
  4. '|' Around is no space without a space with no spaces.
Django template language provides about sixty built-in filter

To be continued ..........................

Guess you like

Origin www.cnblogs.com/17vv/p/11484401.html