Django Template System

Django template (Template) system

official documentation

Template System Basics

Django templates are text strings that separate the presentation of the document from the data. Templates define some placeholders and basic logic (template tags) that dictate how the document should be displayed. Typically, templates are used to generate HTML, but Django templates can generate any text-based format.

grammar

The text enclosed by two pairs of curly braces (eg {{ person_name }}) is a variable, meaning "insert the value of the specified variable here". A pair of curly braces and percent-enclosed text (such as {% if ordered_warranty %}) is a template tag. The definition of tags is fairly broad: anything that allows the templating system to process logic is a tag.

Variables and Methods

{{ variable name}}, the variable name consists of alphanumerics and underscores. The dot (.) has a special meaning in the template language and is used to obtain the corresponding property value of an object.

A few examples: Code in view.py:

def template_test(request):
    l = [11, 22, 33]
    d = {"name": "alex"}

    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def dream(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]
    return render(request, "template_test.html", {"l": l, "d": d, "person_list": person_list})

Supported notation in templates:

# 取l中的第一个参数
{{ l.0 }}
# 取字典中key的值
{{ d.name }}
# 取对象的name属性
{{ person_list.0.name }}
# .操作只能调用不带参数的方法
{{ person_list.0.dream }}

Label

if

{% if %} evaluates the value of the variable, and if it is true (ie exists, not empty, not false), the template system displays the content between {% if %} and {% endif %}. E.g:

{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% endif %}

The {% else %} tag is optional:

{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% else %}
<p>Get back to work.</p>
{% endif %}

An if tag can also have one or more {% elif %} clauses:

{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
<p>Athletes should be out of the locker room soon! </p>
{% elif %}
...
{% else %}
<p>No athletes. </p>
{% endif %}

{% if %} supports the use of and, or, or not to test multiple variables, or to negate a specified variable. E.g:

{% if athlete_list and coach_list %}
<p>Both athletes and coaches are available. </p>
{% endif %}

{% if not athlete_list %}
<p>There are no athletes. </p>
{% endif %}

{% if athlete_list or coach_list %}
<p>There are some athletes or some coaches. </p>
{% endif %}

{% if not athlete_list or coach_list %}
<p>There are no athletes or there are some coaches. </p>
{% endif %}

{% if athlete_list and not coach_list %}
<p>There are some athletes and absolutely no coaches. </p>
{% endif %}

In the same label, and and or can be used at the same time, in this case, and has a higher priority than or. E.g:

{% if athlete_list and coach_list or cheerleader_list %}
# 像这样解释(在if 标签中使用括号是无效的句法。):
if (athlete_list and coach_list) or cheerleader_list

If parentheses are required to indicate precedence, nested if tags should be used. Using parentheses to control the order of operations is not supported. If you find it necessary to use parentheses, consider executing the logic outside the template and passing in the result through a dedicated template variable. Alternatively, use nested {%if %} tags directly, like this:

{% if athlete_list %}
    {% if coach_list or cheerleader_list %}
    <p>We have athletes, and either coaches or cheerleaders! </p>
    {% endif %}
{% endif %}

Every {% if %} must have a matching {% endif %}. Otherwise, Django will throw a TemplateSyntaxError exception.

for

The {% for %} tag is used to iterate over the elements in the sequence. Like Python's for statement, the syntax is for X in Y, where Y is the sequence to iterate and X is the variable used in a single loop. On each iteration, the template system renders the content between {% for %} and {% endfor %}. For example, the following template can be used to display athletes in the athlete_list variable:

<ul>
    {% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
    {% endfor %}
</ul>

Add reversed to the tag to iterate the list in reverse:

{% for athlete in athlete_list reversed %}
...
{% endfor %}

{% for %} tags can be nested:

{% for athlete in athlete_list %}
<h1>{{ athlete.name }}</h1>
<ul>
    {% for sport in athlete.sports_played %}
    <li>{{ sport }}</li>
    {% endfor %}
</ul>
{% endfor %}

If you need to iterate over a list of lists, you can unpack the values ​​in each sublist into separate variables. For example, if the context contains a list of (x,y) coordinate points, called points, the following template can be used to output these coordinate points:

{% for x, y in points %}
<p>There is a point at {{ x }},{{ y }}</p>
{% endfor %}

You can also use this tag if you need to access elements in the dictionary. If the context contains a dictionary data, the following template can be used to display the keys and values ​​of the dictionary:

{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}

Usually, the size of the list is checked before iterating over the list, and if it is empty, some special text is displayed:

{% if athlete_list %}
    {% for athlete in athlete_list %}
    <p>{{ athlete.name }}</p>
    {% endfor %}
{% else %}
    <p>There are no athletes. Only computer programmers.</p>
{% endif %}

This practice is so common that the for tag supports an optional {% empty %} clause that defines what to display when the list is empty. The following example is equivalent to the previous one:

{% for athlete in athlete_list %}
<p>{{ athlete.name }}</p>
{% empty %}
<p>There are no athletes. Only computer programmers.</p>
{% endfor %}

Inside the {% for %} loop, a template variable called forloop can be accessed. This variable has several properties through which some information about the looping process can be obtained:

  • The value of forloop.counter is an integer representing the number of times to loop. The value of this property starts at 1, so the first time through the loop, forloop.counter is equal to 1. Here is an example:
{% for item in todo_list %}
<p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}
  • forloop.counter0 is similar to forloop.counter, but starts at zero. On the first loop, its value is 0.
  • The value of forloop.revcounter is an integer representing the number of elements remaining in the loop. On the first loop, the value of forloop.revcounter is the total number of elements in the sequence to traverse. The value of forloop.revcounter is 1 on the last loop.
  • forloop.revcounter0 is similar to forloop.revcounter, but the index is zero-based. On the first loop, the value of forloop.revcounter0 is the number of elements in the sequence minus one. The value of forloop.revcounter0 is 0 on the last loop.
  • forloop.first is a boolean value that is True the first time the loop is looped. Handy when you need special handling of the first element:
{% for object in objects %}
    {% if forloop.first %}
        ...
    {% else %}
        ...
    {% endif %}
    {{ object }}
        ...
{% endfor %}
  • forloop.last is a boolean value that is True for the last loop. It is often used to place pipe symbols between a set of links:
{% for link in links %}
{{ link }}
{% if not forloop.last %}
    |
{% endif %}
{% endfor %}

The output of the above template code might be: Link1 | Link2 | Link3 | Link4, and is also often used to place commas between groups of words:

<p>Favorite places:</p>
{% for p in places %}
{{ p }}{% if not forloop.last %}, {% endif %}
{% endfor %}
  • In a nested loop, forloop.parentloop refers to the parent loop's forloop object. Here is an example:
{% for country in countries %}
    <table>
        {% for city in country.city_list %}
        <tr>
            <td>Country #{{ forloop.parentloop.counter }}</td>
            <td>City #{{ forloop.counter }}</td>
            <td>{{ city }}</td>
        </tr>
        {% endfor %}
    </table>
{% endfor %}

forloop variables are only available inside the loop. When the template parser encounters {% endfor %}, the forloop disappears.

ifequal/ifnotequal

Templates often need to compare two values ​​and display something when they are equal. For this, Django provides the {% ifequal %} tag. The {% ifequal %} tag compares two values, and if equal, displays the content between {% ifequal %} and {% endifequal %}. The following example compares the template tags user and currentuser:

{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}

Arguments can be hardcoded strings, using either single or double quotes, so the following code is valid:

{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% endifequal %}
    {% ifequal section "community" %}
<h1>Community</h1>
{% endifequal %}

Like {% if %}, the {% ifequal %} tag supports an optional {% else %} clause:

{% ifequal section 'sitenews' %}
<h1>Site News</h1>
{% else %}
<h1>No News Here</h1>
{% endifequal %}

The arguments to {% ifequal %} can only be template variables, strings, integers and decimals. The following are valid examples:

{% ifequal variable 1 %}
{% ifequal variable 1.23 %}
{% ifequal variable 'foo' %}
{% ifequal variable "foo" %}

Other variable types, such as Python dictionaries, lists, or booleans, cannot be hard-coded in {% ifequal %}. The following is an invalid example:

{% ifequal variable True %}
{% ifequal variable [1, 2, 3] %}
{% ifequal variable {'key': 'value'} %}

If you want to test for true or false, you should use the {% if %} tag. ifequal tags can be replaced with if tags and the == operator.

{% ifnotequal %} works like ifequal, but it tests whether two arguments are not equal. ifnotequal tags can be replaced with if tags and the != operator.

Notes

Like HTML and Python, the Django template language supports comments. Comments are marked with {# #}: {# This is a comment #}

If you want to write a multi-line comment, use the {% comment %} template tag like this:

{% comment %}
This is a
multi-line comment.
{% endcomment %}

Comment tags cannot be nested.

Fiter filter

Template filters are an easy way to adjust variable values ​​before displaying them. Filters are specified using pipe notation as follows:

{{ name|lower }}

The above code first adjusts the value of the {{ name }} variable through the lower filter - converting the text to lowercase before displaying it. Filters can be cascaded, that is, passing the output of one filter to the next.

The following example gets the first element in the list and converts it to uppercase:

{{ my_list|first|upper }}

Some filters can accept parameters. Arguments to filters are placed after the colon and are always enclosed in double quotes. E.g:

{{ bio|truncatewords:"30" }}Display the first 30 words of the bio variable.

Template loading mechanism

For loading templates from the file system, Django provides a convenient and powerful API that strives to remove the redundancy of template loading calls and the templates themselves. To use this template loading API, you first need to tell the framework where the template is stored. This location is configured in the settings file, the settings.py file mentioned in the previous chapter on the ROOT_URLCONF setting. Open the settings.py file and find the TEMPLATES setting. Its value is a list, one for each template engine:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            # ... 一些选项 ...
        },
    },
]

The value of BACKEND is a dotted Python path to the template engine class that implements the Django template backend API. The built-in backends are django.template.backends.django.DjangoTemplates and django.template.backends.jinja2.Jinja2.

Because most engines load templates from files, the top-level configuration for each engine contains three common settings:

  • DIRS defines a list of directories in which the template engine looks for template source files in order.
  • APP_DIRS sets whether to look for templates in installed applications. By convention, when APPS_DIRS is set to True, DjangoTemplates will look for a subdirectory named "templates" in each application in INSTALLED_APPS. This allows the template engine to find the application template even if DIRS is empty.
  • OPTIONS are some backend specific settings.

Multiple instances of the same backend can be configured with different options, however this is not common. To define a unique name for each engine.

include (component) template tag

Built-in template tags: {% include %}

The purpose of this tag is to introduce the content of another template. Its parameter is the name of the template to be imported, which can be a variable or a hard-coded string (in quotes, both single and double quotes).

Whenever you want to use the same code in multiple templates, consider using {% include %} to remove duplication. The following example imports the contents of the includes/nav.html template:

{% include 'includes/nav.html' %}

template inheritance

Template inheritance means creating a base "skeleton" template that contains all the common parts of the website, and defining some "blocks" that child templates can override.

First, define a base template, a skeleton, for sub-templates to fill. Here is the base template for the preceding example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>
</html>

We named this template base.html, and it defines a simple HTML document skeleton that is used by all pages in the site. Subtemplates can overwrite the content of the block, add content to the block, or leave it alone. {% block %} tag: Its role is very simple, telling the template engine that sub-templates can cover this part of the content.

After creating the base template, modify the existing current_datetime.html template to use the base template:

{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}

The principle is described below. When the template engine loads the current_datetime.html template, it finds the {% extends %} tag and realizes that this is a child template, so it immediately loads the parent template, which is base.html here.

When the parent template is loaded, the template engine sees three {% block %} tags in base.html and replaces it with the content from the child template. Therefore, the title defined in {% block title %} and the content defined in {% block content %} will be used.

Note that this child template does not define a footer block, so the template system uses the content from the parent template. {% block %} blocks in parent templates are always fallback content.

Inheritance does not affect the context of the template. That is, any template in the inheritance tree can access every template variable in the context. The inheritance hierarchy can be as deep as needed. Inheritance often uses the following three-tier structure:

  • Create a base.html template that defines the overall look and feel of the site. The content of this template rarely changes.
  • Create base_SECTION.html templates (such as base_photos.html and base_forum.html) for each "section" in the site. These templates extend base.html and contain styles and designs specific to each region.
  • Create separate templates for various pages, such as forum pages or photo albums. These templates extend the corresponding area templates.

This is the best way to reuse code and is easy to add content to shared areas, such as common navigation within the same area.

Here are some guidelines for using template inheritance:

  • If there is {% extends %} in the template, it must be the first tag in the template. Otherwise, template inheritance doesn't work.
  • In general, the more {% block %} tags in the base template, the better. Remember that child templates don't need to define all the blocks in the parent template, so it is possible to define reasonable default content for some blocks, and only override the required blocks in the child template. More hooks are always good.
  • If you find that you are writing the same code over and over in multiple templates, it may be an indication that you should move that code to a {%block %} tag in the parent template.
  • If you need to get content from a block in the parent template, use {{ block.super }}, which is a "magic" variable that provides the rendered text in the parent template. This can be done when adding content to a block, rather than completely overwriting it.
  • You cannot define the same name for multiple {% block %} tags in the same template. The reason for this limitation is that block tags are bidirectional. That is, the block tag not only identifies a gap for filling, but is also used to define what fills the gap in the parent template. If there are two blocks with the same name in a template, the parent template doesn't know which block to use.
  • In most cases, the arguments to {% extends %} are strings, but variables can also be used if the name of the parent template is not known until runtime. Through this, some dynamic judgments can be made.

built-in tags

  1. autoescape: Controls the current auto-escaping behavior. The argument to this tag is on or off, indicating whether automatic escaping is in effect within the block. Blocks end with endautoescape tags. When auto-escaping is enabled, variables containing HTML are escaped before output (filters are applied before that). This has the same effect as manually applying the escape filter on each variable. The only exceptions are code that generates variables or is marked as safe content that does not need escaping via a safe or escape filter. Usage example:
{% autoescape on %}
{{ body }}
{% endautoescape %}
  1. block: Defines blocks that can be overridden by child templates.
  2. comment: Ignore everything between {% comment %} and {% endcomment %}. The start tag can add optional comments, such as explaining why the code is commented out. comment tags cannot be nested.
  3. csrf_token: This tag provides CSRF protection. About Cross Site Request Forgery
  4. cycle: Each time this tag is executed, a value in the output parameter is output. The first execution outputs the first parameter, the second execution outputs the second parameter, and so on. After all parameters are output once, return to the first parameter, and then output in turn. This tag is especially useful in loops:
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}

Any number of values ​​(separated by spaces) can be used in a cycle tag. Values ​​enclosed in single quotes (') or double quotes (") are treated as string literals, and those without quotes are treated as template variables. 6. debug: Outputs a lot of debugging information, including the current context and imported modules. 7. extends: Indicates that the template in which it is located extends a parent template. This tag has two uses: {% extends "base.html" %} (with quotation marks), and the literal value "base.html" is the name of the parent template. {% extends variable % } Takes the value of variable as the name of the parent template. If the variable evaluates to a string, Django uses that string as the name of the parent template; if it evaluates to a Template object, Django uses that object as the parent template. 8. filter: Use one or more filters to filter the content block. 9. firstof: Output the first variable value in the parameter that is not False. If the passed variables are all False, nothing will be output. Usage example:

{% firstof var1 var2 var3 %}
# 等效于:
{% if var1 %}
{{ var1 }}
{% elif var2 %}
{{ var2 }}
{% elif var3 %}
{{ var3 }}
{% endif %}
  1. for: Iterates over the elements in the array and assigns the current iteration element to a context variable.
  2. for … emptyThe :for tag has an optional {% empty %} clause that displays some text if the specified array is empty or cannot be found.
  3. if:{% if %} evaluates the value of the variable, if true (i.e. exists, not empty, not false), the content of the output block if tag can have one or more {% elif %} clauses, and a {% else %} clause, displayed when all the preceding conditions fail. These clauses are optional.
  4. ifchanged: Check if the value has changed since the previous iteration. {% ifchanged %} block tags are used in loops. There are two usages: 1- Check the rendered content, compare it with the previous state, and only show the content if there is a change. 2- Check if there is a change in the value of one or more of the specified variables.
  5. ifequal: Output the contents of the block when the two arguments are equal. E.g:
{% ifequal user.pk comment.user_id %}
...
{% endifequal %}
  1. ifnotequal: Similar to ifequal, but tests whether the two parameters are not equal. Can be replaced with if and != operators.
  2. include: Load a template to render in the current context. This is how other templates are brought into the template. The name of the template can be a variable: {% include template_name %}or a hardcoded string (with quotes):{% include "foo/bar.html" %}
  3. load: Load a custom template tag.
  4. lorem: Displays random placeholder Latin text. Can be used to provide sample data for templates. Usage: {% lorem [count] [method] [random] %}The {% lorem %} tag accepts zero, one, two or three arguments. These parameters are: 1-count: A number (or variable) specifying the number of paragraphs or words to generate (defaults to 1). 2-method: is w for words, p for HTML paragraphs, or b for plain text paragraphs (default is b). 3-random: Random output (when specified) when generating text, do not use common paragraphs (Lorem ipsum dolor sit amet…). For example, {% lorem 2 w random %} randomly outputs two Latin words.
  5. now: Displays the current date and/or time in the format specified by the parameter. For example: It is {% now "jS FYH:i" %} The incoming format can also be a predefined value, such as DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT. The output content of the predefined formats varies depending on the current localization settings and whether localized formats are enabled. For example: It is {% now "SHORT_DATETIME_FORMAT" %}
  6. regroup: Regroups a group of similar objects by shared properties. {% regroup %} produces a list of grouped objects. Each grouping object has two attributes: 1-grouper: the basis of the grouping (such as the string "India" or "Japan"), 2-list: the list of elements in the grouping (such as the list of cities where the country is "India"), Any valid template lookup object is a valid grouping property, including methods, properties, keys of dictionaries, and elements of lists.
  7. spaceless: Remove whitespace between HTML tags, including tabs and newlines. Usage example:
{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
# 这个示例返回的 HTML 如下:
<p><a href="foo/">Foo</a></p>
  1. emplatetag: Output the characters that make up the template tag syntax. The template system itself cannot escape, so if you want to display the characters that make up a template tag, you must use the {%templatetag %} tag.
  2. url: Returns the absolute path (URL without domain name) corresponding to the specified view function and optional parameters. Special characters in the path are encoded using iri_to_uri(). Outputting links this way is DRY-compliant because there is no need to hardcode the URL in the template.
  3. verbatim: Don't let the template engine render the content in the block. The JavaScript template layer often uses this tag to prevent conflicts with Django's syntax.
  4. widthratio: Calculates the aspect ratio up to a certain value when inserting images such as bar graphs, and then adjusts the ratio. E.g:<img src="bar.png" alt="Bar" height="10" width="{% widthratio this_value max_value max_width%}" />
  5. with: Cache complex variables under a simple name. This can be done when accessing resource-intensive methods (eg, accessing a database) multiple times. E.g:
{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

Built-in filter

  1. add: Add the parameter to the value. For example: {{ value|add:"2" }}if value is 4, output 6.
  2. addslashes: put a slash before the quotation mark. Can be used to escape strings in CSV. For example: {{ value|addslashes }}if the value is "I'm using Django", output "I'm using Django".
  3. capfirst: Make the first letter of the value uppercase. If the first character is not a letter, this filter has no effect.
  4. center: Centers the value within the specified width. For example: "{{ value|center:"14" }}"if value is "Django", output "␣␣␣␣Django␣␣␣␣" (␣ means a space).
  5. cut: Removes the value specified by the parameter from the string.
  6. date: Format the date using the specified format. For example: {{ value|date:"D d M Y" }}if value is a datetime object (such as the result of datetime.datetime.now()), the output string is similar to "Fri 01Jul 2016". You can also pass in the predefined formats DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT, or SHORT_DATETIME_FORMAT, as well as custom formats using date format specifiers.
  7. default: If value is false, use the specified default value; otherwise, use the value of value. E.g:{{ value|default:"nothing" }}
  8. default_if_none: Use the specified default value if and only if value is None, otherwise use the value of value.
  9. dictsort: Sort the list of dictionaries by the keys specified by the parameter, and return the sorted list. E.g:{{ value|dictsort:"name" }}
  10. dictsortreversed: Sorts a list of dictionaries by the keys specified by the parameter, and returns the reverse-sorted list.
  11. divisibleby: Returns True if the value is divisible by the argument. For example: {{ value|divisibleby:"3" }}if value is 21, return True.
  12. escapejs: Escape characters in JavaScript strings. The results obtained by this filter are not safe to use in HTML, but prevent syntax errors when using templates to generate JavaScript/JSON.
  13. filesizeformat: Format the value to a human-readable file size (eg '13 KB', '4.1 MB', '102 bytes', etc.). For example: {{ value|filesizeformat }}if value is 123456789, output 117.7 MB.
  14. first: Returns the first element in the list.
  15. floatformat: When no parameter is specified, approximate floating-point numbers with only one decimal place (provided there are decimals). If an integer argument is specified, floatformat approximates with the appropriate number of decimal places. If value is 34.23234, {{ value|floatformat:3 }}output 34.232.
  16. get_digit: Retrieve the specified digit from a number, 1 means the lowest digit.
  17. iriencode: Convert IRI (Internationalized Resource Identifier, Internationalized Resource Identifier) ​​into a string suitable for use in URLs.
  18. join: Joins lists using strings, similar to Python's str.join(list).
  19. last: Returns the last element in the list.
  20. length: The length of the return value. Both strings and lists work.
  21. length_is: Returns True if the length of the value is equal to the argument, otherwise returns False. E.g:{{ value|length_is:"4" }}
  22. linebreaks: Replace newlines in plain text with appropriate HTML tags. A newline is replaced with an HTML <br /> tag, and a newline after a newline is replaced with an end-of-paragraph tag (</p>).
  23. linebreaksbr: Replace all newlines in plain text with HTML <br /> tags.
  24. linenumbers: Display text with line numbers.
  25. ljust: Left-justifies the value within the specified width. For example: {{ value|ljust:"10" }}if value is "Django", output "Django␣␣␣␣" (␣ means a space).
  26. lower: Convert the string to all lowercase.
  27. make_list: Convert the value to a list. When the value is a string, returns a list of letters. When the value is an integer, convert the argument to a Unicode string before creating the list.
  28. phone2numeric: Convert a phone number (which may contain letters) to an equivalent numerical value. The input does not need to be a valid phone number, any string can be converted. For example: {{ value|phone2numeric }}if value is 800-COLLECT, output 800-2655328.
  29. pluralize: Returns a complex suffix when the value is not 1. The default suffix is ​​"s". When the pluralization of words is complicated, you can specify singular and plural suffixes, separated by commas. E.g:You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
  30. random: Returns a random element in the specified list.
  31. rjust: Right-justifies the value within the specified width. For example: {{ value|rjust:"10" }}if value is "Django", output "␣␣␣␣Django" (␣ represents a space).
  32. safe: tag string without further HTML escaping before output. This filter has no effect when auto-escaping is turned off.
  33. safeseq: Apply the safe filter to each element in the sequence. Can be combined with other filters that act on sequences (such as join). For example: {{ some_list|safeseq|join:", " }}the safe filter cannot be used directly at this time, because it converts the variable to a string first, rather than processing a single element in the sequence.
  34. slice: Returns a slice of the list. The syntax is the same as Python's list slicing.
  35. time: Format the time using the specified format. Like the date filter, it can be a predefined TIME_FORMAT or a custom format.
  36. timesince: Format the date as a time from a moment (eg "4 days, 6 hours"). There is an optional parameter that specifies the date base point for comparison (if not specified, it is compared with now).
  37. timeuntil: The span from the specified date or datetime.
  38. title: Convert the string to title format, that is, the first letter of the word is capitalized, and the rest of the letters are lowercase.
  39. truncatechars: String is truncated when the string exceeds the specified length. The truncated string ends with a translatable ellipsis (…). E.g:{{ value|truncatechars:9 }}
  40. truncatechars_html: Similar to truncatechars, but knows how to truncate HTML tags.
  41. truncatewords: Truncate the string after the specified number of words.
  42. truncatewords_html: Similar to truncatewords, but knows how to truncate HTML tags.
  43. unordered_list: recursively traverse nested lists, returning an HTML unordered list (without start and end tags).
  44. upper: Convert the string to all uppercase letters.
  45. urlencode: escape for use in URLs.
  46. urlize: Convert URLs and email addresses in text into clickable links. URLs starting with http://, https :// or www. are supported.
  47. urlizetrunc: Like urlize, converts URLs and email addresses into clickable links, but truncates URLs at the specified character length. For example: {{ value|urlizetrunc:15 }}If the value is "Check out www.djangoproject.com", output "Checkout<ahref=" http://www.djangoproject.com"rel="nofollow ">www.djangopr…</a>". Like urlize, this filter should only be applied to plain text.
  48. wordcount: Returns the number of characters.
  49. wordwrap: Wrap the line at the specified length.
  50. yesno: Maps True, False and None (optional) to the strings "yes", "no", "maybe", or to the list passed in as parameters (separated by commas), and returns according to the true and false values the corresponding string. E.g:{{ value|yesno:"yeah,no,maybe" }}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325364558&siteId=291194637