django-Template Language and filters

Source: Internet
Author: User

Django Template language

The first template is just a text file that generates any text-based format (HTML, XML, CSS, etc.), contains variables in the template, replaces it with the final value when the template is rendered, and labels that control the logic of the template.

The variable uses {{variable name}}, and the logical operation uses {% tag%}.

Simple Basic Template code:

{% extends"base_generic.html"%}{% block title%}{{section.title}}{% endblock%}{% Block content%}{% forStoryinchStory_list%}"{{Story.get_absolute_url}}">{{Story.headline|Upper}} </a>" -"}}</p>{% ENDFOR%}{% Endblock%}
Django template Basic SyntaxOne, variable

The variable looks like this {{ variable}} : . when the template engine encounters a variable, it evaluates the variable and replaces it with the final value. Variable names consist of underscores, letters, and numbers. Point (.) Also appears in the variable section, but has a special meaning, using the dot (.) To access the properties of the variable.

When the template engine encounters a point (.) , you try to find it in the following order:

Dictionary key property or method numeric index

If the point (.) After the function name is called without arguments, and the parentheses are omitted, the final result of the variable is the return value of the function.

It is important to note that if the key is named ' Items ' in the dictionary, the value of item in the dictionary will be given instead of the. Items () method of the calling dictionary.

Get the value of a variable demo:

<! DOCTYPE html>"en">"UTF-8"> <title> Template Language usage </title> <meta name="Viewport"Content="Width=device-width, initial-scale=1.0">Single Variable<span style="color:red;">{{Variable Value}}</span>: {{name}}</p>List variable: {{name_list}}<br>the list can be indexed in a way that name_list.0\name_list the value.1: {{name_list.0}}<br>the list can be indexed in a way that name_list.0\name_list the value.1: {{Name_list.1}}<br></p>Dictionary variable: {{name_dict}}<br>dictionary variable access via. Key Name_dict.first_name: {{name_dict.first_name}}<br>dictionary variable access via. Key Name_dict.last_name: {{name_dict.last_name}}<br>The dictionary is unordered and cannot be indexed by name_dict.0:{{name_dict.0}}<br></p>pass an object p1:{{p1}}<br>pass an object p2:{{P2}}<br>P1 Name: {{p1.name}},p1 age:{{p1.age}}<br>P2 Name: {{p2.name}},p2 age:{{p2.age}}<br></p>How to List objects: obj_list.0-&GT;P1 Obj_list.0.name/age: <br>P1 Name: {{obj_list.0.name}}<br>P1 Age: {{obj_list.0.age}}&LT;BR&GT;&LT;/P&GT;&LT;HR style="color:red;"></body>a single variable, list, dictionary, object

Second, the label

The label looks like this {% tag %}. First, tags are more complex than variables, some perform logical judgments, loop traversal, and others load external information into the template for later use. Some tags need to start tag and end tag {% tag%} .... {% Endtag%}. Django comes with about 20 built-in template tags. You can Read all the content about them in the built-in tag reference . Here are just a few common tags:

for

loops through each item in the array. For example, to display the following list of available athletes athlete_list :

<ul>{ for in athlete_list%}    <li>{{athlete.name}}< /li>{% endfor%}</ul>
For ... empty forThe label is provided with an optional{% empty %} clauses so that when the given group is empty or not found, you can do something about it.
<ul>{ for in user_list%}    <li>{{user.name}}</li>{ % empty%}    <li> empty </li>{% endfor%}</ul>
If,else,elif

Evaluates a variable that displays the contents of the block if the variable is "true":

if athlete_list%} number of    athletes: {{athlete_list|  Length}}{elif athlete_in_locker_room_list%}    athletes should be out of the locker hostel soon!{ else %}    No athletes.{ % ENDIF%}

on top, if athlete_list is not empty, the number of players will be displayed by the variable . Otherwise, if it is not empty, the "athlete should be out ..." message is displayed. If two lists are empty, "no athletes". will be displayed.

The IF statement supports and, or, = =, >, <,! =, <=, >=, in, not-in, is, is-not judgment.

withusing 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.
{% with total=business.employees.count%}    {{Total}} employee{{Total |  Pluralize}}{% endwith%}
Third, Filter

Use filter to modify the displayed variables.

The filter looks like this: {value|filter: ' ... '}. Value is the variable to be modified, filter is the function of the filters, and the colon (after:) is the argument. Django provides about 60 built-in template filters. You can Read all the content about them in the built-in filter reference . to let you know what features are available, here are some of the more commonly used template filters:

Defalue

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

{{value|default:"Nothing" }}

if value is not provided or is empty, the above will show " nothing ".

length

returns the length of the value. This applies to strings and lists. For example:

{{Value|length}}

If value is [' A ', ' B ', ' C ', ' d '], the output will be 4.

Filesizefamat

a value that is formatted as a "human readable" file size (that is, , , and so on). For example:‘13 KB‘‘4.1 MB‘‘102 bytes‘

{{Value|filesizeformat}}

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

again, these are just a few examples; Please see full list of the built-in filter reference .

You can also create your own custom template filters;

Iv. Custom Filter

1. First you need to create a templates directory (package) in the app directory

Need to note:

After you add the Templatetags module, you need to restart the server before you can use a label or filter in the template.

2. Create a py file that contains custom labels and filters:

polls/    __init__. py    models.py    templatetags/        __init__. PY        poll_extras.py    views.py

In your template, you can introduce custom tags and filters in the following ways:

{% load Poll_extras%}

3. Import Template

 from Import Template

4. Generate a registrar, which is a template. Library () instance

Register = template. Libraty ()

5. Writing a custom template filter

 #   Write a custom filter that does not accept parameters  def   add_a (arg1):  return
      " {}_a   " .format (arg1)  #   Write a custom filter that takes parameters  def   add (ARG1,ARG2):  return   " {}_{}   " .format (ARG1,ARG2)   ARG1: is a required parameter, the VALUEARG2 to be modified before the pipe is accepted: is the parameter passed by the user, the filter colon after the  "  

6. Self-Test custom filter

@register. Filter (name='AddA')#Registering a custom filterdefadd_a (arg1):return '{}_a'. Format (arg1) @register. Filter (name='Add')#Registering a custom filterdefAdd (ARG1,ARG2):return '{}_{}'. Format (ARG1,ARG2)

7. Using Custom Filters

1. First import {% load myfilter%} # in the page   Load the custom filter py file under the templates package {% load myfilter%}2   '123'|  '123'|add:'abc' } The end result is: 123ABC

3. Need to restart the server
Wu, Simpletag

is 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 #} {% plus "1" "2" "ABC"%}
Vi. Inclusion_tag returns an HTML fragment

More for returning HTML code snippets

Example:

templatetags/my_inclusion.py

From django Import templateregister = template. Library () @register. Inclusion_tag (' result.html ') def show_results (n):    n = 1 if n < 1 else int (n)    data = ["{} key". Format (i) for I in range (1, n+1)]    return {"Data": Data}

Templates/snippets/result.html

<ul>  {% for choice in data%}    <li>{{choice}}</li>  {% endfor%}</ul>

Templates/index.html

<! DOCTYPE html>

django-Template Language and filters

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.