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:
- Dictionary lookup (Dictionary lookup)
- Property or method query (Attribute or method lookup)
- Digital index query (Numeric index Lookup)
Precautions:
- 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.
- 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.
- Filter supports the "chain" operation. I.e., a filter output as input to another filter.
- Filters can accept parameters, for example: {{sss | truncatewords: 30}}, which will display the first 30 words of sss.
- 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: ','}}
- '|' Around is no space without a space with no spaces.
To be continued ..........................