Django template System (top)

Source: Internet
Author: User
Tags alphanumeric characters truncated

Filters    Filter Default    substitution action Filesizeformat    format Human readable add    to variable add parameter lower    lowercase upper    uppercase title    Title Ljust    left-justified rjust    right-aligned center center    length    Returns the length of value slice    slice    first takes one element    last Take the last element join  string stitching truncatechars    truncate date    date format Safe    label Escape custom filtertagsfor    for loop some parameters available for ... emptyif, elif, and Elsewith    define an intermediate variable Csrf_token

Common syntax

Only two special symbols need to be recorded in the Django template

{{}} and {%}

{{}} represents a variable , which is replaced with a value when the template is rendered, and{%} represents a logically related operation .

Variable

{{variable name}}

Variable names consist of alphanumeric characters and underscores.

The point (.) has a special meaning in the template that gets the response property value of the object.

View in code:

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})
View Code

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}}

Note: When the template system encounters a (.), it is queried in the following order:

1. Querying in the dictionary

2. Properties or methods

3. Digital Index

Filters

Translate to filter to modify the display result of the variable

Syntax: {{value| Filter_name: Parameter}}

"| There are no spaces around! No space!! ”

Default

{{value|default:"Nothing" }}

Show nothing if value is not passed

Note: The options of templates can add an option: String_if_invalid: ' Cannot find ', can replace the role of default.

Filesizeformat

Format the value as a "human readable" file size (e.g. "13KB", "4.1MB", etc.). For example

{{Value|filesizeformat}}

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

Add

Adding parameters to a variable

{{value|add:'2' }}

Value is the number 4, the output is 6.

{{First|add:second}}

If first is "second" and "4,5,6", the output is "1,2,3,4,5,6".

Lower

Lowercase

{{Value|lower}}

Upper

Capital

{{Value|upper}}

Title

Title

{{Value|title}}

Ljust

Align Left

" {{value|ljust:'ten'}} "

Rjust

Align Right

" {{value|rjust:'ten'}} "

Center

Center

" {{value|center:""}} "

Length

{{Value|length}}

Returns the length of value, such as value=[' a ', ' B ', ' C ', ' d ', to show 4

Slice

Slice

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

First

Take the first element

{{Value|first}}

Last

Take the last element

{{Value|last}}

Join

Use string concatenation lists. Str.join (list) with Python.

{{value|join:'"}}

Truncatechars

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

Parameters: Number of characters truncated

{{Value|truncatechars:9}}

Date

Date formatting

{{value|date:"y-m-d h:i:s"}}

A visual output character: Click to view

Safe

The Django template escapes the 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}}

Custom Filter

The custom filter is just a Python function with one or two parameters:

* The value of the variable (input)---is 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 placement:

app01/    __init__. py    models.py    templatetags/  #  Create a new package under APP01 Package        __init__. py        app01_filters.py   #  Build a py file that holds the custom filter    views.py

Writing a custom filter

 from Import  = template. Library () @register. Filterdef  Fill (value, arg):    return value.replace ("  ", Arg) @register. Filter (Name="addsb")  def  ADD_SB (value):    return"{} sb". Format (value)

Using a custom filter

{#  pilot into our custom filter file #} {% load app01_filters%} {#  using our custom filter #} {{somevariable|fill:'__'  }}{{d.name|ADDSB}}

Tags

For

< ul > {% for user in user_list%}     < Li > {{User.Name}} </ Li > {% endfor%} </ ul >

Some parameters available for the For loop:

Variable description
for Loop.counter index value of the current loop (starting from 1)
foo loop.counter 0 index value of the current loop (starting from 0)
for Loop.revcounter the reverse index value of the current loop (starting at 1)
for loop.revcounter 0 Reverse index value for current loop (starting from 0)
for Loop.first The current loop is not the first loop (boolean value)
for loop.last current loop is not the last loop (Boolean)
for Loop.pare Ntloop outer loop of this layer

For ... empty

< ul > {% for user in user_list%}     < Li > {{User.Name}} </ Li > {% empty%}     < Li > empty </li>{% endfor%}</ul  >

If,elif and Else

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

Of course, you can have only if and else

{% if user_list|length > 5}  Seven seater deluxe suv{% else%}    Rickshaw {% endif%}

If statement supports And,or,==,>,<,!=,<=,>=,in,not In,is,is not judged

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%} on the from form of the page

Comments

# ... #

Precautions

1.The Django template language does not support continuous judgment, that is, the following notation is not supported :

{% If a >b >c%}  ... {% ENDIF%}

2. The precedence of attributes in the Django template language is greater than the method

defXX (Request): D= {"a": 1,"b": 2,"C": 3,"Items":" -"}    returnRender (Request,"xx.html",{"Data":D})

As above, when we render a page using the Render method, the dictionary D has a key that is items and has the default D.items () method, which in the template language:

{{Data.items}}

The value of the items key of D is taken by default

Django template System (top)

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.