Django Template language
Official Document Link: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#std: Templatetag-for
Common syntax
Variable correlation: {{}}
Logical correlation: {%%}
Variable correlation
Syntax: {{variable name}}
Variable name naming specification: variable names consist of numbers, letters, and underscores.
The point (.) has a special meaning in the template language, which is used to get the corresponding property values of the object.
The wording in view:
deftemplate_test (Request): L= [11, 22, 33] D= {"name":"Alex"} classPerson (object):def __init__(self, Name, age): Self.name=name Self.age= AgedefDream (self):return "{} is Dream ...". Format (self.name) Alex= Person (name="Alex", age=34) Egon= Person (name="Egon", age=9000) Eva_j= Person (name="Eva_j", age=18) Person_list=[Alex, Egon, Eva_j]returnRender (Request,"template_test.html", {"L"L"D": D,"person_list": Person_list})
Supported notation in templates:
{# takes the first parameter in L #} {{l.0}}{# takes the value of key in the dictionary #} {{D.name}}{# takes object's Name property #} {{Person_list.0.name}}{# . Operation can only invoke a method without parameters #} {{Person_list.0.dream}}
Filters
Syntax: {{value|filter_name: parameter}}
Default
" Nothing "}}
Show nothing if value is not passed
Length
Syntax: {{value|length}}
| No spaces on either side
Returns the ' value ' length. For example, value = [3]
Filesizeformat
Format the value as a "human-readable" file size (for example,, ‘13 KB‘
‘4.1 MB‘
, and ‘102 bytes‘
so on). For example:
{{Value|filesizeformat}}
If value is 123456789, the output will be 117.7 MB.
Slice
Slice
{{value|slice:'2:-1'}}
Date
Format time
{{value|date:"y-m-d h:i:s"}}
Safe
The Django template automatically escapes syntax tags such as HTML tags and js, for obvious reasons, for security. But sometimes we may not want these HTML elements to be escaped, such as we do a content management system, the background is added to the article is decorated, these decorations may be a similar to the FCKeditor editor to fill the HTML modifier text, If auto-escaping, the source file that protects the HTML tag is displayed. There are two ways to turn off automatic HTML escaping in Django, and if it's a separate variable, we can tell Django that this code is safe without escaping with the filter "|safe".
Like what:
Value = "<a href= ' # ' > Dot me </a>"
{{Value|safe}}
Truncatechars
If the number of string characters is more than the specified number of characters, it is truncated. The truncated string will be displayed as a translatable ellipsis ("...").
Syntax: number of characters truncated by value|
{{value|truncatechars: +}}
Custom Filter
The custom filter is just a Python function with one or two parameters:
- The value of the variable (input)--not necessarily a string
- The value of the parameter-this can have a default value, or completely omit
For example, in the filter {{var | foo: "Bar"}}, the filter foo will pass the variable var and the parameter "bar".
Custom filter code file save location:
app01/ __init__. py models.py templatetags/ # Create a new python under APP01 Package__init__. py app01_filters.py # build a file to store your custom filter views.py
Writing a custom filter method
fromDjangoImportTemplateregister=template. Library () @register. Filter (name="Cut")defCut (Value, arg):returnValue.replace (ARG,"") @register. Filter (name="ADDSB")defADD_SB (value):return "{} SB". Format (value)
Using the custom filter method
{# pilot into our custom filter file #} {% load app01_filters%} {# using our custom filter #} {{somevariable|cut:"0" }}{{d.name|ADDSB}}
Tagsfor
<ul>{ for in user_list%} <li>{{user.name}}</li> {% endfor%}</ul>
Some parameters available for the For loop:
Variable |
Description |
forloop.counter |
Index value of the current loop (starting at 1) |
forloop.counter0 |
Index value of the current loop (starting at 0) |
forloop.revcounter |
Reverse index value of the current loop (starting at 1) |
forloop.revcounter0 |
Reverse index value of the current loop (starting at 0) |
forloop.first |
The current loop is not the first loop (Boolean value) |
forloop.last |
The current loop is not the last loop (Boolean value) |
forloop.parentloop |
Outer loop of this layer loop |
For ... empty
<ul>{ for in user_list%} <li>{{user.name}}</li>{ % empty%} <li> empty </li>{% endfor%}</ul>
If,elif&else
if user_list%} number of users: {{user_list| Length}}{elif black_list%} blacklist number: {{black_list| Length}}{else %} no user {% endif%}
If, else
if user_list|length > 5} seven seater luxury suv{else %} Rickshaw {% endif%}
The IF statement supports and, or, = =, >, <,! =, <=, >=, in, not-in, is, is-not judgment.
With
Define an intermediate variable
{% with total=business.employees.count%} {{Total}} employee{{Total | Pluralize}}{% endwith%}
Csrf_token
This tag is used for cross-site request forgery protection.
Write {% Csrf_token%} in the form form on the page
Comments
{#.............#}
Master version
<! DOCTYPE html>"en">"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%}{% Block Page-main%}{% Endblock%}{% Block Page-js%}{% Endblock%}</body>Note: We usually define the CSS blocks and JS blocks for the page in the motherboard, which is convenient for the sub-page substitution.
Inherit MasterUse the following syntax to inherit the motherboard at the top of the page in the sub-page
{% Extend ' Master name. HTML '%}
Fast (Block)Define "blocks" by using them in the master board {% block xxx %}
.
Replace the corresponding contents in the motherboard by defining the block name in the master board in the sub-page.
{% block Page-main%} <p> Thin </p> <p> human evil </p> <p> rain send Dusk flower easy Fall </p>{% endblock%}
ComponentYou can save commonly used page content such as navigation bar, footer information and other components in a separate file, and then in the place you need to use the following syntax to import.
' navbar.html ' %}
Static file-related{% load static%}""images/hi.jpg" %} " alt="hi! " />
When referencing a JS file, use:
{% load static%}<script src=""mytest.js" %}"> </script>
Multiple uses of a file can be saved as a variable name
{% load static%}{"images/hi.jpg" as Myphoto%}<img src=" {{Myphoto}}'></img>
Using Get_static_prefix{% load static%}<img src="{% get_static_prefix%}images/hi.jpg" alt=" hi! " />
Or
{% load static%}{% get_static_prefix as Static_prefix%}<img src="{{Static_prefix}} Images/hi.jpg" alt="hi! " /><img src="{{static_prefix}}images/hi2.jpg" alt=" Hello! " />
Custom Simpletagis similar to a custom filter, except that it receives more flexible parameters.
Define register Simple Tag
@register. Simple_tag (name="plus")def Plus (A, B, c): return " {} + {} + {} ". Format (A, B, c)
Use the custom simple tag
{% load App01_demo%} {# Simple Tag #} " 1 " " 2 " " ABC " %}
Inclusion_tagMore for returning HTML code snippets
Example:
templatetags/my_inclusion.py
fromDjangoImportTemplateregister=template. Library () @register. Inclusion_tag ('result.html')defshow_results (n): N= 1ifN < 1Elseint (n) Data= ["Item {}". Format (i) forIinchRange (1, n+1)] return{"Data": Data}
Templates/snippets/result.html
<ul> {for in data%} <li>{{choice }}</li> {% endfor%}</ul>
Templates/index.html
<! DOCTYPE html>"en">"UTF-8"> <meta http-equiv="x-ua-compatible"Content="Ie=edge"> <meta name="Viewport"Content="Width=device-width, initial-scale=1"> <title>inclusion_tag test</title>{% Load Inclusion_tag_test%}{% show_results 10%}</body>Django Template language