Django [Part 3]: Part III template syntax (important !!!) The syntax of the Django framework Django template

First, what is a template?

As long as there is not a html template syntax in a html file inside, this file is called a template.

Second, the template syntax classification

First, the syntax of template variables: {{}} The syntax is:

Key traversing complex data structures in Django templates is the dot character. (Ie points)

views.py

Copy the code
def index(request):
    name = "hello haiyan"
    i = 200
    l = [11,22,33,44,55]
    d = {"name":"haiyan","age":20}

    class People(object): #继承元类
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def __str__(self):
            return self.name+str(self.age)
        def dream(self):
            return "你有梦想吗?"
    #实例化
    person_egon = People("egon",10)
    person_dada = People("dada",34)
    person_susan = People("susan",34)
    person_list = [person_dada,person_egon,person_susan]

    return render(request,"index.html",
                    {
                        "name":name,
                        "i": i, 
                        "L": L, 
                        "d": d, # key corresponds to the template name. It is as defined above corresponding to the value of the variable 
                        "person_egon": person_egon, 
                        "person_dada": person_dada, 
                        "person_list": person_list, 
                    } 
              ) 
    # return the render (Request, "index.html", about locals ()) 
    # with about locals () can do not write the above render. But with locals (), views inside with what name. What you have inside the template name with 
    # locals () local: with the locals had to follow the above is equivalent to that
Copy the code

template/index.html

Copy the code
<h4> variable {{z}}: Depth query </ H4> <HR> 
<H3> {{name}} </ H3> 
<P> {{I}} </ P> 
<P> {{L} } </ P> 
<P> {} {D} </ P> 
<P> {} {} l.0 ------ "may be a single value taken by the symbol period (i.e. point) </ p> 
<P> L.4 {{}} </ P> 
<P> d.name {{}} </ P> 
<P> {} {} d.age ----- "The dictionary may break period value, a point to get. 
However, the front page is not see your template syntax when you click on an element of the review 
, you will find that secretly change over the </ the p-> 
<the p-> person_dada.name {{}} </ the p- > 
<P> person_egon.age {{}} </ P> 
<P> person_dada.dream {{}} </ P> <-!. method, when attention is currently no method of dream parameters -> 
<p> {{person_list.2}} </ p> <-! single value -> 
<P> person_list.1.name {{}} </ P> 
<! - how to make it become the object string it? 
In which the index view function plus a built-in method __str__ -> <--__ str__ string is subject to change -!>
Copy the code

Note: The method of symbol period (no parametric method) may be used to reference the object.

<h4>字典:{{ dic.name.upper }}< / h4>

Second, the label template syntax: syntax {% tag%}:

Tag looks like this:  {% tag %}. Tag is more complex than a variable: some additional information creating in the output text, a number or to control flow through the logic loop, some variables will be used to load subsequent to the template.

Some tags require the start and end tags (e.g., {% tag %} ...tag content ... {% endtag%}).

1, for the label (Note: cycle number {} {forloop} can be displayed through)

Copy the code
<h3> cycle value. 1 </ H3> <HR> 
{%}% for Item in person_list 
    <P> item.name, for {{}}, {{}} item.age </ P> 
{%} endfor% 

< h3> cycle value 2: descending </ h3> <HR> 
{% for person_list Item in the reversed%} 
    <- start sequence number from 1 ->! 
    <P> {} {} forloop.counter ----- > item.name, for {{}}, {{}} item.age </ P> 
    <-! numbers start with 0 -> <p> {{forloop.counter0 }} -----> {{item .name}}, {{item.age} } </ p> <-! descending number -> <p> {{forloop.revcounter }} -----> {{item.name}}, { item.age}} {</ P> 
{%} endfor% 

<H3> cycle 3 value: Dictionary </ H3> <HR> 
{% for K, V in d.items%} 
    <P> {{K} }, {{V}} </ P> 
{%} endfor%
Copy the code

2, .... for empty: for  label with an optional {%  empty  %}  clause set forth in order to empty or is not found, the operation may be.

{% for person in person_list %}
    <p>{{ person.name }}</p>

{% empty %}
    <p>sorry,no person here</p>
{% endfor %}

3、if标签 :{% if %}会对一个变量求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。

Copy the code
% IF I {> 300%} 
    <P> {I}} is greater than {</ P> 
{%}% elif 200 is I == 
    <P> is equal to {I}} {</ P> 
{%}% the else 
    <P > less than {I}} {</ P> 
{%} endif%
Copy the code

4, with: Use a simple name cache a complex variable , when you need to use an "expensive" method (such as database access) many times when it is very useful

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}
<p>{{ person_list.2.name }}</p>
{% with name=person_list.2.name %}
    <p>{{ name }}</p>
{% endwith %}

5, csrf_token: the label for protection CSRF

When submitting data security mechanisms will do when you click on the submit a forbbiddon will be 
wrong, it is to use the setting in the configuration of security mechanisms scrf do, then we can now give it a ,,, comments 
or form form add a {% csrf_token%} Here ,,, 
this is the real solution, not a solution of the comment
<h3>scrf_token</h3><form action="/tag/" method="post">
    {% csrf_token %}
    <p><input type="text" name="haiyan"></p>
    <input type="submit">
</form>

Third, the filter template syntax: syntax {{obj | filter__name: param}}

1、default:If a variable is false or empty, the default values ​​given. Otherwise, use the value of the variable. E.g:

<P> default filter: {{li | default: "If the content is empty explanatory, display settings"}} </ p>

2, length: returns the length value. It works both strings and lists. E.g:

{{ value|length }}

If the value is [ 'a', 'b', 'c', 'd'], the output is 4.

3、filesizeformat:Value formatted as a "human readable" file size (e.g.  '13 KB''4.1 MB''102 bytes', etc.). E.g:

{{ value|filesizeformat }}

If  value is 123456789, the output will be  117.7 MB.  

4、date:如果 value=datetime.datetime.now()

{{ value|date:"Y-m-d" }}  

5, slice: Slice

If the value = "hello world"

{{ value|slice:"2:-1" }}

6, truncatechars cut

If the string of characters is more than a specified number of characters, it will be truncated. Translatable strings will be truncated sequence at the end of the ellipsis ( "...").

Parameters: the number of characters to be truncated

E.g:

<p> Truncated characters: {{Content | truncatechars: 20 is}} </ P> 
<p> Truncated words: {{content | truncatewords: 4 }} </ p>

If the content is "I am is haiyan, how are you asd df dfgfdgdg?

Output: Truncated character: I am is haiyan, ho ...

Output: Truncated words: I am is haiyan, how ...

7、safe

JS and HTML tags will be syntactic tags Django template automatically escapes, for obvious reasons, this is for safety. But sometimes we might not want these HTML elements are escaped, for example, we do a content management system, add background of the article is modified, these modifications may be raised by a similar FCKeditor editing the HTML modifier text, escaped, then automatically displayed if the source file is to protect HTML tags. To turn off the automatic Django escaped HTML in two ways, if it is a single variable we can filter | tell Django "safe" way to secure this code is not necessary to escape. such as:

value="<a href="">点击</a>"

{{ value|safe}}
<p> {{label}} </ p> <-! tag to the security system will become string -> 
<P> {{label | safe}}! </ P> <- plus safe , make sure your data is safe in order to be treated as a tag ->

Here are some simple common filter templates, more detailed

Fourth, custom tags and filters

1, INSTALLED_APPS in the current configuration settings in the app, django otherwise unable to find simple_tag custom.

2. Create templatetags module app in (name of the module can only be templatetags )

3, in templatetags which create any .py file,

Such as: my_tags.py

Copy the code
Template Django Import from 
from django.utils.safestring Import mark_safe 
 
Register = () is the name #register template.Library is fixed, unchangeable
@ register.filter filter 
DEF Multi (X, Y):
return X * Y

@ register.simple_tag tag
DEF Multitag (X, Y, Z):
return X * Y * Z
@register.simple_tag  标签
def my_input(id,arg):
   result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
   return mark_safe(result)
Copy the code

4, before using import custom filter simple_tag and html files created my_tags.py

{% load my_tags %} 

5, using simple_tag and filter (how to call)

Filter: {{var | filter_name:}} # parameters only two parameters, a parameter is a variable var, a parameter that is behind parameters

tags: {% simple_tag Parameter 1 Parameter 2 ...%}

Copy the code
. ------------------------------- HTML 
{%}% Load XXX   
      
# 12 is NUM = 
{{NUM | Multi: 2 24-#}} 
 
{{num | Multi: "[22,333,4444]"}} is equivalent to copy, and it [22,333,4444] multiplied by the num times
{% Multitag 2 5 6%} parameters are not limited, but can not be placed if for statements {% simple_tag_multi num 5%}

Copy the code
Customizable parameters only two filter functions, can be logically Analyzing 
custom label without parameter limits, the logic can not be determined
{% If i | multi: 5 > 1000%}! <- . 5 * Analyzing I> 1000 -> 
    <P> {I}} is greater than {</ P> 
{%}% the else 
    <P> is greater than or equal to {{ }} I </ P> 
{%} endif%

 



First, what is a template?

As long as there is not a html template syntax in a html file inside, this file is called a template.

Second, the template syntax classification

First, the syntax of template variables: {{}} The syntax is:

Key traversing complex data structures in Django templates is the dot character. (Ie points)

views.py

Copy the code
def index(request):
    name = "hello haiyan"
    i = 200
    l = [11,22,33,44,55]
    d = {"name":"haiyan","age":20}

    class People(object): #继承元类
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def __str__(self):
            return self.name+str(self.age)
        def dream(self):
            return "你有梦想吗?"
    #实例化
    person_egon = People("egon",10)
    person_dada = People("dada",34)
    person_susan = People("susan",34)
    person_list = [person_dada,person_egon,person_susan]

    return render(request,"index.html",
                    {
                        "name":name,
                        "i": i, 
                        "L": L, 
                        "d": d, # key corresponds to the template name. It is as defined above corresponding to the value of the variable 
                        "person_egon": person_egon, 
                        "person_dada": person_dada, 
                        "person_list": person_list, 
                    } 
              ) 
    # return the render (Request, "index.html", about locals ()) 
    # with about locals () can do not write the above render. But with locals (), views inside with what name. What you have inside the template name with 
    # locals () local: with the locals had to follow the above is equivalent to that
Copy the code

template/index.html

Copy the code
<h4> variable {{z}}: Depth query </ H4> <HR> 
<H3> {{name}} </ H3> 
<P> {{I}} </ P> 
<P> {{L} } </ P> 
<P> {} {D} </ P> 
<P> {} {} l.0 ------ "may be a single value taken by the symbol period (i.e. point) </ p> 
<P> L.4 {{}} </ P> 
<P> d.name {{}} </ P> 
<P> {} {} d.age ----- "The dictionary may break period value, a point to get. 
However, the front page is not see your template syntax when you click on an element of the review 
, you will find that secretly change over the </ the p-> 
<the p-> person_dada.name {{}} </ the p- > 
<P> person_egon.age {{}} </ P> 
<P> person_dada.dream {{}} </ P> <-!. method, when attention is currently no method of dream parameters -> 
<p> {{person_list.2}} </ p> <-! single value -> 
<P> person_list.1.name {{}} </ P> 
<! - how to make it become the object string it? 
In which the index view function plus a built-in method __str__ -> <--__ str__ string is subject to change -!>
Copy the code

Note: The method of symbol period (no parametric method) may be used to reference the object.

<h4>字典:{{ dic.name.upper }}< / h4>

Second, the label template syntax: syntax {% tag%}:

Tag looks like this:  {% tag %}. Tag is more complex than a variable: some additional information creating in the output text, a number or to control flow through the logic loop, some variables will be used to load subsequent to the template.

Some tags require the start and end tags (e.g., {% tag %} ...tag content ... {% endtag%}).

1, for the label (Note: cycle number {} {forloop} can be displayed through)

Copy the code
<h3> cycle value. 1 </ H3> <HR> 
{%}% for Item in person_list 
    <P> item.name, for {{}}, {{}} item.age </ P> 
{%} endfor% 

< h3> cycle value 2: descending </ h3> <HR> 
{% for person_list Item in the reversed%} 
    <- start sequence number from 1 ->! 
    <P> {} {} forloop.counter ----- > item.name, for {{}}, {{}} item.age </ P> 
    <-! numbers start with 0 -> <p> {{forloop.counter0 }} -----> {{item .name}}, {{item.age} } </ p> <-! descending number -> <p> {{forloop.revcounter }} -----> {{item.name}}, { item.age}} {</ P> 
{%} endfor% 

<H3> cycle 3 value: Dictionary </ H3> <HR> 
{% for K, V in d.items%} 
    <P> {{K} }, {{V}} </ P> 
{%} endfor%
Copy the code

2, .... for empty: for  label with an optional {%  empty  %}  clause set forth in order to empty or is not found, the operation may be.

{% for person in person_list %}
    <p>{{ person.name }}</p>

{% empty %}
    <p>sorry,no person here</p>
{% endfor %}

3、if标签 :{% if %}会对一个变量求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。

Copy the code
% IF I {> 300%} 
    <P> {I}} is greater than {</ P> 
{%}% elif 200 is I == 
    <P> is equal to {I}} {</ P> 
{%}% the else 
    <P > less than {I}} {</ P> 
{%} endif%
Copy the code

4, with: Use a simple name cache a complex variable , when you need to use an "expensive" method (such as database access) many times when it is very useful

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}
<p>{{ person_list.2.name }}</p>
{% with name=person_list.2.name %}
    <p>{{ name }}</p>
{% endwith %}

5, csrf_token: the label for protection CSRF

When submitting data security mechanisms will do when you click on the submit a forbbiddon will be 
wrong, it is to use the setting in the configuration of security mechanisms scrf do, then we can now give it a ,,, comments 
or form form add a {% csrf_token%} Here ,,, 
this is the real solution, not a solution of the comment
<h3>scrf_token</h3><form action="/tag/" method="post">
    {% csrf_token %}
    <p><input type="text" name="haiyan"></p>
    <input type="submit">
</form>

Third, the filter template syntax: syntax {{obj | filter__name: param}}

1、default:If a variable is false or empty, the default values ​​given. Otherwise, use the value of the variable. E.g:

<P> default filter: {{li | default: "If the content is empty explanatory, display settings"}} </ p>

2, length: returns the length value. It works both strings and lists. E.g:

{{ value|length }}

If the value is [ 'a', 'b', 'c', 'd'], the output is 4.

3、filesizeformat:Value formatted as a "human readable" file size (e.g.  '13 KB''4.1 MB''102 bytes', etc.). E.g:

{{ value|filesizeformat }}

If  value is 123456789, the output will be  117.7 MB.  

4、date:如果 value=datetime.datetime.now()

{{ value|date:"Y-m-d" }}  

5, slice: Slice

If the value = "hello world"

{{ value|slice:"2:-1" }}

6, truncatechars cut

If the string of characters is more than a specified number of characters, it will be truncated. Translatable strings will be truncated sequence at the end of the ellipsis ( "...").

Parameters: the number of characters to be truncated

E.g:

<p> Truncated characters: {{Content | truncatechars: 20 is}} </ P> 
<p> Truncated words: {{content | truncatewords: 4 }} </ p>

If the content is "I am is haiyan, how are you asd df dfgfdgdg?

Output: Truncated character: I am is haiyan, ho ...

Output: Truncated words: I am is haiyan, how ...

7、safe

JS and HTML tags will be syntactic tags Django template automatically escapes, for obvious reasons, this is for safety. But sometimes we might not want these HTML elements are escaped, for example, we do a content management system, add background of the article is modified, these modifications may be raised by a similar FCKeditor editing the HTML modifier text, escaped, then automatically displayed if the source file is to protect HTML tags. To turn off the automatic Django escaped HTML in two ways, if it is a single variable we can filter | tell Django "safe" way to secure this code is not necessary to escape. such as:

value="<a href="">点击</a>"

{{ value|safe}}
<p> {{label}} </ p> <-! tag to the security system will become string -> 
<P> {{label | safe}}! </ P> <- plus safe , make sure your data is safe in order to be treated as a tag ->

Here are some simple common filter templates, more detailed

Fourth, custom tags and filters

1, INSTALLED_APPS in the current configuration settings in the app, django otherwise unable to find simple_tag custom.

2. Create templatetags module app in (name of the module can only be templatetags )

3, in templatetags which create any .py file,

Such as: my_tags.py

Copy the code
Template Django Import from 
from django.utils.safestring Import mark_safe 
 
Register = () is the name #register template.Library is fixed, unchangeable
@ register.filter filter 
DEF Multi (X, Y):
return X * Y

@ register.simple_tag tag
DEF Multitag (X, Y, Z):
return X * Y * Z
@register.simple_tag  标签
def my_input(id,arg):
   result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
   return mark_safe(result)
Copy the code

4, before using import custom filter simple_tag and html files created my_tags.py

{% load my_tags %} 

5, using simple_tag and filter (how to call)

Filter: {{var | filter_name:}} # parameters only two parameters, a parameter is a variable var, a parameter that is behind parameters

tags: {% simple_tag Parameter 1 Parameter 2 ...%}

Copy the code
. ------------------------------- HTML 
{%}% Load XXX   
      
# 12 is NUM = 
{{NUM | Multi: 2 24-#}} 
 
{{num | Multi: "[22,333,4444]"}} is equivalent to copy, and it [22,333,4444] multiplied by the num times
{% Multitag 2 5 6%} parameters are not limited, but can not be placed if for statements {% simple_tag_multi num 5%}

Copy the code
Customizable parameters only two filter functions, can be logically Analyzing 
custom label without parameter limits, the logic can not be determined
{% If i | multi: 5 > 1000%}! <- . 5 * Analyzing I> 1000 -> 
    <P> {I}} is greater than {</ P> 
{%}% the else 
    <P> is greater than or equal to {{ }} I </ P> 
{%} endif%

 



Guess you like

Origin www.cnblogs.com/mqhpy/p/11203985.html