Django's template (T)

First, the common syntax

Django templates only need to remember two special symbols:

{{ }}with{% %}

{} {} Represents a variable, the value is replaced when rendering template, {%}% indicates the operation of logically related.

A variable

Syntax: variable name}} {{

Variable names consist of alphanumeric and underscores.

Dot (.) Has a special meaning in the template language, corresponding to the acquired attribute of the object.

A few examples:

view code:

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

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

        def dream(self):
            return "{} is dream...".format(self.name)

    sun = Person(name="孙悟空", age=34)
    zhu = Person(name="猪八戒", age=90)
    sha = Person(name="沙和尚", age=18)

    person_list = [sun, zhu, sha]
    return render(request, "template_test.html", {"l": l, "d": d, "person_list": person_list})

Template support wording:

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

Note: (.) ​​When the system encounters a template, will be in the following order to query:

  1. Query in the dictionary
  2. Property or method
  3. Index numbers (No, i.e. from the back can not be found is negative)

Two, Filters-- filter

Translation of the filter, to display results of modified variables.

Syntax: {{value | filter_name: Parameter}} ':' no space left

default

{{ value|default:"nothing"}}

If the value is not passed, then the value will show nothing

Note: TEMPLATES The OPTIONS can add an option: string_if_invalid: 'find', can replace the default action of the (higher priority than the default).

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'string_if_invalid': '找不到'
        },
    },
]

filesizeformat

Value formatted as a "human readable" file size (e.g. '13 KB ',' 4.1 MB ',' 102 bytes', etc.). E.g:

{{ value|filesizeformat }}

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

add

Was added to the variable parameters corresponding to + for addition, splicing digital string, combined list

{{ value|add:"2" }}

4 is a digital value, the output is 6.

{{ first|add:second }}

If the first is [1, .2,3], second is [4,5,6], the result is that the output [1,2,3,4,5,6].

lower与upper

lower case

{{ value|lower }}

capital

{{ value|upper}}

title

title

{{ value|title }}

bright, rjust, center

Left

"{{ value|ljust:"10" }}"

Align Right

"{{ value|rjust:"10" }}"

Center

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

length

{{ value|length }}

Returns the value of the length, such as the value = [ 'a', 'b', 'c', 'd'], then, 4 is displayed.

slice

Sliced, and the slices using the same method as python, the step size may be provided

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

first,last

Take the first element

{{ value|first }}

Take the last element

{{ value|last }}

join

Using string concatenation list. str.join with the python (list).

{{ value|join:" // " }}

truncatechars,truncatewords

If the string of characters is more than a specified number of characters, it will be truncated. Translatable strings will be truncated sequence at the end of the ellipsis ( "...").

参数:截断的字符数
{{ value|truncatechars:9}}
参数:截断的单词数(空格区分)
{{ value|truncatewords:9}}

date

Date Format

{{ value|date:"Y-m-d H:i:s"}}

settings in the configuration, change the default format:

USE_L10N = False
DATETIME_FORMAT = 'Y-m-d H:i:s'

Characters formatted output: Click to view .

safe

JS and HTML tags will be syntactic tags Django template automatically escapes, for obvious reasons, this is 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 we can filter | tell Django "safe" way to secure this code is not necessary to escape.

E.g:

value = "<a href='#'>点我</a>"
{{ value|safe}}

Py file is provided in the safe (html in the need to use safe):

from django.utils.safestring import mark_safe
'a':mark_safe('<a href="http://www.baidu.com">百度</a>')
{{ a }}

Third, custom filter

Custom filters with only one or two parameters Python functions:

  • (Inputs) the value of - - it is not necessarily a string
  • Values ​​of the parameters - which can have a default value, or omitted entirely,

For example, in the filter {{var | foo: "bar "}} , the filter foo pass variables var and parameters "bar" .

Custom filter code file placement:

app01/
    __init__.py
    models.py
    templatetags/  # 在app01下面新建一个package package
        __init__.py
        app01_filters.py  # 建一个存放自定义filter的py文件
    views.py

Writing a custom filter:

from django import template
register = template.Library()

@register.filter
def fill(value, arg):
    return value.replace(" ", arg)

@register.filter(name="addSB")  # 起了个别名
def add_sb(value):
    return "{} SB".format(value)

Use a custom filter:

{# 先导入我们自定义filter那个文件 #}
{% load app01_filters %}

{# 使用我们自定义的filter #}
{{ somevariable|fill:"__" }}
{{ d.name|addSB }}

Two, Tags tag

for

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

The for loop parameters are available:

Variable Description
forloop.counter Loop current index value (starting at 1)
forloop.counter0 Loop current index value (zero)
forloop.revcounter Reverse current loop index (1 to end)
forloop.revcounter0 Reverse circulating current index value (0 to end)
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 of outer loop cycles

for ... empty

<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% empty %}
    <li>空空如也</li> //for循环取不出数据时显示
{% endfor %}
</ul>

if...elif和else

{% if user_list %}
  用户人数:{{ user_list|length }}
{% elif black_list %}
  黑名单数:{{ black_list|length }}
{% else %}
  没有用户
{% endif %}

if...else

{% if user_list|length > 5 %}
  七座豪华SUV
{% else %}
    黄包车
{% endif %}

if语句支持 andor==><!=<=>=innot inisis not判断

with

A definition of intermediate variables

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}
//或
{% with business.employees.count as total %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

csrf_token

This tag is used CSRF protection.

In the form in the form of a page on which writing {% csrf_token%}

Generating a hidden input tag, name = 'csrfmiddlewaretoken' '

<input type="hidden" name="csrfmiddlewaretoken" value="5n5puGXmCwdIRReChMg7jIx8neIMZYsKevahly05qn3TrFh4gRJGFh6aKTqyUf2Y">

Note

{# ... #}

Precautions

  1. Django template language does not support continuous judgment that does not support the following wording:
{% if a > b > c %}  // 使用a > b and b > c
...
{% endif %}
  1. Priority attribute of Django template language is greater than the method
def xx(request):
    d = {"a": 1, "b": 2, "c": 3, "items": "100"}
    return render(request, "xx.html", {"data": d})

As above, when using the render method to render a page, pass a dictionary d key items and there is a default d.items () method, this time in the template language:

{{ data.items }}

Default items key will take the d.

Third, the motherboard

First, extract the motherboard

  1. html page, extract the public part of multiple pages
  2. Define multiple block blocks need to fill in a sub-page coverage
<!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 %}  //母板的CSS样式位置
  
  {% endblock %}
</head>
<body>

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

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

{% endblock %}
</body>
</html>

Note: typically define special page in the block and the motherboard CSS JS block to facilitate the sub-page replacement.

Second, inherited motherboard

In the sub-page using the following syntax at the top of the page to inherit the motherboard.

{% extends 'layouts.html' %}  // 带上引号   不带的话会当做变量
// 重写block块 ,写在block内部

Third, the block (block)

By using the master {% block xxx %}to the definition of "block."

In the sub-pages correspond to replace the mother board by defining the contents of the corresponding block name in the motherboard.

{% block page-main %}
  <p>一</p>
  <p>二</p>
  <p>三</p>
{% endblock %}

Fourth, the component

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

{% include 'navbar.html' %}

Fifth, the static files related

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

Use when referencing JS files:

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

Many were used in a file can be saved as a variable:

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

Use get_static_prefix:

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

or

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

Six custom simple_tag

Custom filter and the like, may receive more flexible parameters

Registration is defined simple_tag:

@register.simple_tag
def plus(a, b, c):
    return "{} + {} + {}".format(a, b, c)

Use custom simple tag:

{% load app01_demo %}

{# simple tag #}
{% plus "1" "2" "abc" %}

七, inclusion_tag

Html code used for dynamic return fragment

Example:

// templatetags/my_inclusion.py

from django import template

register = template.Library()

@register.inclusion_tag('result.html')
def show_results(n):
    n = 1 if n < 1 else int(n)
    data = ["第{}项".format(i) for i in range(1, n+1)]
    return {"data": data}
// templates/result.html:
<ul>
  {% for choice in data %}
    <li>{{ choice }}</li>
  {% endfor %}
</ul>
// templates/index.html:
<!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>inclusion_tag test</title>
</head>
<body>

{% load my_inclusion %}

{% show_results 10 %}
</body>
</html>

Guess you like

Origin www.cnblogs.com/douzi-m/p/12146468.html