[] Django template system

@
Official documentation two special symbols: {} {} == == == {% and%} == variables associated with {} {}, using {logically related%%}.



A variable

Click the syntax used in the Django template language: {{variable name}}

** When the template engine encounters a variable, it will calculate this variable, and then replace itself with the results.
Named variables include any alphanumeric and the underscore (_) combination.
Variable names can not contain spaces or punctuation. * *

(.) Point has a special meaning in the template language, when the template system encounters a point, it queries the following order:

  1. Field queries (Dictionary lookup)
  2. Property or method query (Attribute or method lookup)
  3. Digital index query (Numeric index lookup)

Precautions:

  1. == If the value of the calculation results are callable will be called with no arguments, calling the result will be the value of the template. ==
  2. == If the variables do not exist, the template system will insert the value string_if_invalid option, the default value of this option is an empty string. ==

A simple example:

from django.shortcuts import HttpResponse, render, redirect


def template_test(request):
    lst = ['a', 'b', 'c', 'd']

    dct = {
        'name': 'zyk',
        'sex': 'boy',
        'hobby': ['Python', 'Django', 'MySQL']
    }

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

        def blogging(self):
            return '%s is blogging.' % self.name

    zyk = Person('zyk', 'boy')
    xhh = Person('xhh', 'girl')
    xmm = Person('xmm', 'girl')
    person_list = [zyk, xhh, xmm]

    return render(
        request,
        'template_test.html',
        {
            'lst': lst,
            'dct': dct,
            'person_list': person_list
        }
    )

Template can be written:

Lst index taking a value of 0:
== == {{}} # A lst.0
take a value in the name of dct:
== {{}} == # Zyk dct.name
Hobby dct taken in the list of index value of 1:
== {{}} == # dct.hobby.1 the Django
taken person_list index object 2 name:
== {{}} == # person_list.2.name XMM
call in person_list the method of blogging object index 0:
== {{}} == # Zyk person_list.0.blogging iS blogging.

Second, the filter Filters

In Django template language by using filters to change the display of variables.

Syntax: == {{variables | filtration method: Parameter}} ==
wherein: the pipe character (|) is used to apply the filter, colon (:) is for specifying parameters of the filter.

Precautions:

  1. Filter supports "chain" operation, i.e., a filter output can be used as input to another filter.
  2. Filters can accept parameters, for example: {{value | truncatewords: 30}}, the display indicates values ​​of the first 30 words.
  3. Filter parameter contains a space, it must be wrapped in quotes, commas and spaces such as the use splice element list: {{list | join: ','}}.
  4. == pipe symbol (|) == no spaces on either side.
    ***

    1. default

    The default value specified variable.
    Syntax: == value | default: "Default" ==

If a variable is false or null, will be given default values. Otherwise, use the value of the variable.

Note: The
within OPTIONS in the TEMPLATES in the settings.py file can add an option to specify a default value (priority higher than default):
'string_if_invalid': "默认值",
***

2. length

The return value of the length of the string and acting on the list.
Syntax: == value | length ==
***

3. filesizeformat

The value formatted as a "human-readable" file size.
Syntax: == value | filesizeformat ==
***

4. slice

Slice
syntax == value | Slice: "2: -1" ==
***

5. add

Added to the end value of the specified value, if all numbers, the addition.
Syntax: == value | the Add: "add value" ==
***

6. first、last

Take the first element, taking the last element.
When the cycle can be used to judge whether the first or last value.
***

7. join

Using string concatenation list.
Syntax: == value | the Join: "string" ==
***

8. truncatechars

If the string of characters is more than a specified number of characters, it will be truncated. Ellipsis sequence truncated strings will be translated ( "...") at the end (note: "... 'is three characters).
Syntax: == value | truncatechars: 9 ==
***

9. truncatewords

Truncates the string after a certain number of words.
Syntax: == value | truncatewords ==

10. date

Date Format
Syntax: == value | DATE: 'H Ymd: I: S' ==

Character can be formatted output
***

11. safe

JS and HTML tags will be syntactic tags automatically escapes the Django template, for obvious reasons, for safety.

But sometimes we might not want these HTML elements are escaped, for example, we do a content management system, add background of the article is modified, these modifications may be raised by a similar FCKeditor editing the HTML modifier text, escaped, then automatically displayed if the source file is to protect HTML tags.

To turn off the automatic Django escaped HTML in two ways, if it is a single variable that we can pass through the filter (value | safe) way to tell Django code does not have to be a safe escape.

For example: value = "<a href='#'></a>"
***

12. cut

Remove all the same specified character string.
Syntax: == value | Cut: 'Space' ==
***

13. lower、upper、title、ljust、rjust、center

Followed by: all lowercase, all uppercase, title, left justified, right justified, centered
***

14. Custom filter

Custom filters with only one or two parameters Python functions:

  • Value of the variable (input): a string is not necessarily
  • Values ​​of the parameters: there may be a default value, or omitted entirely

For example, in the filter {{var | func: 'var'}}, the filter passes the variable var func parameter and 'bar'.

Custom filter code file storage location:
== In a new app called templatetags package, and then create a custom filter files in the package == below.

Custom filter file written as follows:

from django import template
register = template.Library()

@register.filter(name='addSB')
def add_sb(value):
    return '%s is SB' % value

Calling Custom filter:

{# 先导入自定义的filter文件 #}
{% load 文件名 %}

{# 使用自定义的filter #}
{{value|addSB }}

15. Tags

for
<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% endfor %}
</ul>

Some parameters are available for circulation:
| Variable | the Description |
| - | - |
| forloop.cunter | current index value cycle (starting at 1) |
| forloop.cunter0 | loop current index value (zero) |
| forloop.revcounter | reverse current index value cycle (starting at 1) |
| forloop.revcounter0 | reverse current index value cycle (starting from 0) |
| forloop.first | the current cycle is not the first cycle (boolean value) |
| forloop.last | the current cycle is not the last cycle (Boolean value) |
| forloop.parentloop | this layer cycle of the outer loop |

for ... empty
<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% empty %}
    <li>空空如也</li>
{% endfor %}
</ul>
if ... else
{% if user_list|length > 5 %}
  七座豪华SUV
{% else %}
    黄包车
{% endif %}
if ... elif ... else
{% if user_list %}
  用户人数:{{ user_list|length }}
{% elif black_list %}
  黑名单数:{{ black_list|length }}
{% else %}
  没有用户
{% endif %}

== if statement supports: and, or, ==,> , <, =, <=,!> =, in, not in, is, is not judged ==.
== but! Django template language does not support continuous judgment that does not support the following wording: ==

{% if a > b > c %}
...
{% endif %}
with

A definition of intermediate variables

{% with value as v %}
    {{ v }}
{% endwith %}

16. csrf_token

For cross-site request forgery protection.
If the form is submitted the form, you must write inside the form tag:
== csrf_token% {%} ==

Third, the motherboard

Example (master file: base.html, as follows):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="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 %}
</head>
<body>

<h1>这是母板的标题</h1>
{% block page-main %}
{% endblock %}

<h1>母板底部内容</h1>
{% block page-js %}
{% endblock %}
</body>
</html>

Note: We usually define the page dedicated block in the motherboard CSS and JS block to facilitate sub-page replacement.
***

Template inheritance

Example (Example succession on the master):

{% extends 'base.html' %}

Block (block)

By using == {% block xxx%} == in the master to the definition of "block".
In the sub-pages to the corresponding master replace the corresponding contents in the block by defining the name of the motherboard.

E.g:

{% block page-css %}
...
{% endblock %}

{# 这是母板的标题 #}
{% block page-main %}
...
{% endblock %}

{# 母板底部内容 #}
{% block page-js %}
...
{% endblock %}


Fourth, the component

Common page content, such as navigation, footer information components may be stored in a separate file, and then introduced into the following syntax can be used where necessary.

{% include "文件全名" %}

Example (introduction nav.html code within the file in the file base.html):
Here Insert Picture Description

Fifth, the static files related

== Get settings file from STATIC_URL = '/ static /' and the relative path splicing. ==

{% load static %}
<img src="{% static 'images/hi.jpg' %}" alt="Hi!"/>

Use when referencing JS files:

{% <script src="{% static 'mytest.js' %}"></script> %}

If a file to be used at the same time many can be saved as a variable:

{% load static %}
{% static 'images/hi.jpg' as myphoto %}
<img src="{{ myphoto }}"><img>

Example (import bootstrap file):
Here Insert Picture Description
***

Use get_static_prefix

== Get settings file from STATIC_URL = '/ static /' and the relative path splicing. ==

{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!" />

# 或者

{% 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!" />

Example (bootstrap file import):
Here Insert Picture Description


Custom simpletag_tag

Slightly
***

Custom inclusion_tag

1. Create a named == tmplatetags == packet at the python package App.
2. py new file in the package (eg: mytags.py)
3. edit file, the following steps:
Here Insert Picture Description



Guess you like

Origin www.cnblogs.com/gqy02/p/11304567.html