Django Template Layer

Source: Internet
Author: User
Tags truncated

Python templates: HTML code + template syntax

defCurrent_time (req):#================================ The original view function    #Import datetime    #Now=datetime.datetime.now ()    #html= "    #================================django Template modified view function    #From django.template import Template,context    #Now=datetime.datetime.now ()    #t=template ('     ##t =get_template (' current_datetime.html ')    #c=context ({' current_date ': str (now)})    #Html=t.render (c)    #    #return HttpResponse (HTML)    #Another way of writing (recommended)    Importdatetime Now=Datetime.datetime.now ()returnRender (req,'current_datetime.html', {'current_date': Str (now) [: 19]})

1, template syntax variables

The key to traversing complex data structures in a Django template is the period character, syntax:

{{Var_name}}

views.py:

defIndex (Request):Importdatetime s="Hello"L=[111,222,333]#Listdic={"name":"Yuan"," Age": 18}#DictionaryDate = Datetime.date (1993, 5, 2)#Date Object    classPerson (object):def __init__(self,name): Self.name=name Person_yuan=person ("Yuan")#Custom class ObjectsPerson_egon=person ("Egon") Person_alex=person ("Alex") Person_list=[Person_yuan,person_egon,person_alex]returnRender (Request,"index.html",{"L"L"DiC":d IC,"Date":d ate,"person_list":p erson_list})

Template

Note: A period character can also be used to refer to an object's methods (no parameter method):

2, common filter of several templates

Grammar:

{{Obj|filter__name:param}}

Default

If a variable is false or empty, the given default value is used. Otherwise, the value of the variable is used. For example:

{{value|default:"Nothing" }}

length:
返回值的长度。对字符串和列表都起作用。
{{Value|length}}

如果 value 是 [‘a‘, ‘b‘, ‘c‘, ‘d‘],那么输出是 4。

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

 
{{value|date:'y-m-d' }}

Slice

If value= "Hello World"

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

Truncatechars

If the string character is more than the specified number of characters, it is truncated. The truncated string ends with a translatable sequence of ellipses ("...").

Parameters: Number of characters to truncate
For example:

{{Value|truncatechars:9}}

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=""> click </a>"
{{Value|safe}}

3, the label of the template

The label looks like this: {% tag %} . Tags are more complex than variables: Some create text in the output, some control the flow through loops or logic, and some of the additional information that is added to the template is used by the variables that are loaded later. Some labels need to start and end tags (for example ...). {% tag %} Label content ... {% endtag %} ).

or label
To iterate through each of the elements:

You can use the {% for obj in list reversed %} reverse loop to complete.
Traverse a dictionary:

{% for key,val in dic.items%}    <p>{{Key}}:{{val}}</p>{% endfor%}

Note: The loop sequence number can be displayed by {{Forloop}}

Forloop.counter the current iteration of the            loop (1-indexed) Forloop.counter0 The current iteration of the           Lo OP (0-indexed) Forloop.revcounter         from the end of the loop (1 -indexed) Forloop.revcounter0        from the end of the loop (0-indexed) Forloop.first              if   is The first time through the loopforloop.last                if  was the last time through the loop

 

For ... empty:

 for  in person_list%}    <p>{{person.name}}</p>{% empty%}    <p >sorry,no person here</p>{% endfor%}

If label:

{% if %}Evaluates a variable, if its value is "True" (exists, is not NULL, and is not a Boolean value of false), the corresponding content block is output.

if or num < 0}    <p> invalid </p>{elif and num <%}     <p> Excellent </p>{else %}    <p> get live </p>{% endif%}

With:

Using a simple name to cache a complex variable is useful when you need to use an "expensive" method (such as accessing a database) many times.

For example:

{% with total=business.employees.count%}    {{Total}} employee{{Total |  Pluralize}}{% endwith%}

Csrf_token
This tag is used for cross-site request forgery protection

4, Custom labels and filters

1. Installed_apps in Settings Configure the current app, or Django cannot find a custom simple_tag.
2, create the Templatetags module in the app (module name can only be templatetags)
3. Create any. py file, such as: my_tags.py

 fromDjangoImportTemplate fromDjango.utils.safestringImportMark_safe Register= Template. Library ()#The Register's name is fixed and cannot be changed .@register. FilterdefFilter_multi (v1,v2):returnV1 *v2<br>@register. Simple_tagdefSimple_tag_multi (v1,v2):returnV1 *v2<br>@register. Simple_tagdefMy_input (id,arg): Result="<input type= ' text ' id= '%s ' class= '%s '/>"%(Id,arg,)returnMark_safe (Result)

4. Import the previously created my_tags.py in an HTML file that uses custom Simple_tag and filter

{% load my_tags%}

5. Using Simple_tag and filter (How to call)

-------------------------------. html  {% load xxx%}          #  num=12  #    {{num|filter_multi:"[22,333,4444]"  }}  {% Simple_tag_multi 2 5%}  parameter is not limited, but cannot be placed in the IF for statement  {% simple_tag_multi num 5}

Note: Filter can be used after the IF statement, Simple_tag can not

if num|filter_multi:30 >%}    {{num|filter_multi:30 }}{% endif%}

6, template inheritance (extend)

The most powerful and complex part of the Django template engine is the template inheritance. Template inheritance lets you create a basic "skeleton" template that contains all the elements in your site, and can define blocks that can be overwritten by a quilt template.

Example:

<! DOCTYPE html>"en">"stylesheet"href="Style.css"/> <title>{% block title%}my amazing site{%/span> endblock%}</title>"Sidebar">        {% Block Sidebar%}        <ul> <li><a href="/">Home</a></li> <li><a href="/blog/">Blog</a></li> </ul>        {% Endblock%}    </div> <div id="content">        {% block content%}{% Endblock%}    </div></body>

This template, which we call a base.html, defines a simple HTML skeleton that can be used for two-column layout pages. The work of the "sub-template" is to fill the empty blocks with their contents.

In this example, the block tag defines three blocks that can be filled with template content. Block tells the template engine that the sub-template may overwrite these locations in the template template.
The sub-template may look like this:

" base.html " %} {% block title%}my amazing blog{% endblock%} {% block content%} {for 
   
    in blog_entries%
    }    {% endfor%}
    {% endblock%}
   

The extends tag is the key here. It tells the template engine that the template "Inherits" another template. When the template system processes the template, first, it locates the parent template-in this case, the "base.html".
At that time, the template engine will notice the three block tags in the base.html and replace them with the contents of the sub-template. Depending on the value of the blog_entries, the output might look like this:

<! DOCTYPE html>"en">"stylesheet"href="Style.css"/> <title>my amazing blog</title>"Sidebar"> <ul> <li><a href="/">Home</a></li> <li><a href="/blog/">Blog</a></li> </ul> </div> <div id="content">  isMy first entry.</p>  isMy second entry.</p> </div></body>

Note that the sub-template does not have a sidebar block defined, so the system uses the values from the parent template. The content in the parent template's {% block %} label is always used as an alternative (fallback).
This approach maximizes the reuse of code and makes it easier to add content to a shared content area, for example, partial-scope navigation.
Here are some hints for using inheritance:

    • If you use a tag in a template {% extends %} , it must be the first tag in the template. In any other case, template inheritance will not work.
    • The more labels you set in the base template, the better {% block %} . Keep in mind that the sub-template does not have to define all the blocks in the parent template, so you can populate the most blocks with the appropriate default content, and then define only the one you need. A little more hooks is better than a little bit less.
    • If you find yourself copying content in a large number of templates, it might mean that you should move the content to one of the parent templates {% block %} .
    • If you need to get the content of the block from the parent template, the variable would do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using is not being automatically escaped (see the next sections), since it was already escaped, if necessary, In the parent template.
    • For better readability, you can also give your {% endblock %} label a name. For example:
    • {% block content%} ... {% endblock content%}

You cannot define multiple block tags of the same name in one template.

Django Template Layer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.