Django template system

Official documentation link: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#std:templatetag-for

Just remember two special symbols:

{{ }}and {% %}

Use {{}} for variables related, and {%%} for logically related ones.

 

{{ variable name}}

Variable names consist of alphanumerics and underscores.

The dot (.) has a special meaning in the template language and is used to obtain the corresponding property value of an object.

A few examples:

Code in view:

def Test(request):
    from datetime import datetime
    now=datetime.now()
    name = ' yimi ' 
    age = 25 
    hobbly_list =[ ' Ding Song ' , ' Playing ' , ' Daze ' ]
    hobbly_dict ={ ' yimi ' : ' Daze ' , ' haha ​​' : ' Listen to songs ' , ' wawa ' : ' Play ball ' }
    file_size=131413141314
    blog='<a href="http://www.cnblogs.com/liwenzhou/p/7931828.html">点我</a>'
    file='daishdfkanf riwyjlasdnakjfhqiuwryqcscnaksdfhlairyqi sfjdskdfhiubvaidkaw'

    class Person():
        def __init__(self,name,age):
            self.name=name
            self.age=age

        def __str__(self):
            return  ' My name is %s, this year is %s ' % (self.name, self.age) #The self. attribute must be added to the built-in method
    yimi =Person( ' yimi ' , 25 )
    haha=Person('haha',26)
    wawa = Person ( ' wawa ' , 28 )
    person_list=[yimi,haha,wawa]

    return render(request,'test.html',{
        'name':name,
        'age':age,
        'hobbly_list':hobbly_list,
        'person_list':person_list,
        'file_size':file_size,
        'now_time':now,
        'blog':blog,
        'file':file
    })

Supported notation in templates:

{# Take the first parameter in l#}
{{ hobbly_list.0 }}
{# Get the value of the key in the dictionary#}
{{ d.name }}
{# Get the name property of the object#}
{{ person_list.0.name }}
{# .Operations can only call methods without parameters#}
{{ person_list.0.dream }}

Syntax: {{ value|filter_name:parameter}}

Code in templates:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Experiment</title>
</head>
<body>
{{ name }}
<hr>
{{ age }}
<hr>
<ul>
    {% for hobbly in hobbly_list %}
        <li>{{ hobbly }}</li>
    {% endfor %}
</ul>
<hr>
<ul>
    {% for person in person_list %}
        <li>{{ person.name }}</li>
        <li>{{ person.age }}</li>
        <li>{{ person }}</li>
    {% endfor %}
</ul>
<hr> 
{{names | default : ' No such variable '   }}
#If the value(names) is not passed, the default parameters will be displayed: ' No such variable ' 
<hr> 
{{name | length }}
# ' | ' There is no space on the left and right, no space, no space, no space, and the length of the value is returned. For example, if value='yimi ' , it will display 4.

<hr>
{{file_size|filesizeformat}}
#Format the value to a "human readable" file size (eg ' 13 KB ' , ' 4.1 MB ' , ' 102 bytes ' , etc.)
 <hr> 
{{ name | slice : ' 1:3 ' } }
{{ age|slice:'0:1' }}
#Slice#Number types cannot be sliced
<hr>
{{ now_time|date:'Y-m-d H-i-s' }}
#Formatting is converted into a format we can read at a glance: year, month, day, hour, minute, second
<hr>
{{ blog|safe }}
{{ blog }}
#For security. Django's templates will automatically escape HTML tags and JS and other syntax tags. If you do not want to be escaped, add safe after the value.
<hr>
{{ file }}
<hr> 
{{ file | truncatechars : 9 }} 
#
The number of characters must be added after truncatechars
#If the string has more characters than the specified number of characters, it will be truncated. The truncated string will end with a translatable ellipsis sequence ("..."). <hr> </body> </html>

Results displayed on the page

A custom filter is just a Python function with one or two arguments:

  • The value of the variable (input) - not necessarily a string
  • the value of the parameter - this can have a default value, or be omitted entirely

For example, in filter {{var|foo:"bar"}}, filter foo will be passed the variable var and the parameter "bar" .

 

Custom filter code file placement:

 

 

result:

for

<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% endfor %}
</ul>

Some parameters available for for loop:

for ... empty

If the class iteration object of the loop has no value, then take the content below empty

<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% empty %}
    <li>空空如也</li>
{% endfor %}
</ul>

 if,elif和else

{% if user_list %}
  Number of users: {{ user_list | length }}
{% elif black_list %}
  Number of blacklists: {{ black_list | length }}
{% else %}
  no user
{% endif %}

Of course, you can also only have if and else

{% if user_list|length > 5 %}
  Seven-seat luxury SUV
{% else %}
    rickshaw
{% endif %}

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。

with

Defining an intermediate variable is equivalent to giving a variable an alias

<p>
    {% with hobbly=hobbly_dict.yimi %}
        {{ hobbly }}
    {% endwith %}

</p> 
Result: in a
daze

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325689528&siteId=291194637