Django's template system

grammar

About templates to render you only need to remember two special symbols (syntax)

{{ }}with{% %}

Variable associated with {{}}, {logic associated with %%}.

variable

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

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

  Depth inquiry stronghold symbol (.) Has a special meaning in the template language. When the template system encounters a dot ( "."), It will be in this order inquiries:

   Dictionary lookup (Dictionary lookup)
   property or method query (Attribute or method lookup)
   digital index query (Numeric index lookup)

Precautions:

  1. If the value of calculation result is called, it will be invoked with no parameters. Result of the call will be the value of the template.
  2. If variables does not exist, the system will insert the value string_if_invalid template option, which is the default setting is '' (the empty string).

view.py code

def index(request):
    import datetime
    s = "hello"
    l = [111, 222, 333]  # 列表
    dic = {"name": "yuan", "age": 18}  # 字典
    date = datetime.date(1993, 5, 2)  # 日期对象

    class Person(object):
        def __init__(self, name):
            self.name = name
        def dream(self):
            return 'dreamer'
    person_yuan = Person("chao")  # 自定义类对象
    person_egon = Person("yantao")
    person_alex = Person("jinxin")

    person_list = [person_yuan, person_egon, person_alex]

    return render(request, "index.html", {"l": l, "dic": dic, "date": date, "person_list": person_list})
    # return render(request,'index.html',locals())
    #locals()获取函数内容所有的变量,然后通过render方法给了index.html文件进行模板渲染,如果你图省事,你可以用它,但是很多多余的变量也被传进去了,效率低

Template support wording

<h4>{{s}}</h4>
<h4>列表:{{ l.0 }}</h4>
<h4>列表:{{ l.2 }}</h4>
<h4>字典:{{ dic.name }}</h4>
<h4>日期:{{ date.year }}</h4>

<!--取列表的第1个对象的name属性的值-->
<h4>类对象列表:{{ person_list.0.name }}</h4>
<!--取列表的第1个对象的dream方法的返回值,如果没有返回值,拿到的是none-->
<h4>类对象列表:{{ person_list.0.dream }}</h4>
注意:
    调用对象里面的方法的时候,不需要写括号来执行,并且只能执行不需要传参数的方法,如果你的这个方法需要传参数,那么模板语言不支持,不能帮你渲染

filter

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

  The syntax of the filter: {{value | filter_name: Parameter}}

  Use pipe symbol "|" applying a filter.

  For example: {{name | lower}} then the variable name will show its value after the application of lower filter. lower in action here is all lowercase text.

  Precautions:

  1. Filter supports the "chain" operation. I.e., a filter output as input to another filter.
  2. Filters can accept parameters, for example: {{sss | truncatewords: 30}}, which will display the first 30 words of sss.
  3. Filter parameter contains a space, it must be wrapped in quotes. Such as comma and a space used to connect the elements of a list, such as: {{list | join: ','}}
  4. '|' Around is no space without a space with no spaces
    length  -- 获取数据长度,没参数 
    返回值的长度,作用于字符串和列表
    {{ value|length }}
    
    default -- 设置默认值
    如果一个变量是false或者为空,使用给定的默认值。 否则,使用变量的值。
    {{ value|default:"nothing"}}
    
    filesizeformat -- 将数字转换成可读的表示
    将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB', '4.1 MB', '102 bytes', 等等)
    {{ value|filesizeformat }}
  
  slice -- 切片
  切片,如果 value="hello world",还有其他可切片的数据类型
  {{value|slice:"2:-1"}}
  
    date -- 时间格式化
  格式化,如果 value=datetime.datetime.now()
  {{ value|date:"Y-m-d H:i:s"}}
  
  safe -- 让标签字符串识别成标签 (脚本攻击--xss)
  很多网站,都会对你提交的内容进行过滤,一些敏感词汇、特殊字符、标签、黄赌毒词汇等等,你一提交内容,人家就会检测你提交的内容,如果包含这些词汇,就不让你提交,其实这也是解决xss攻击的根本途径
  {{ value|safe}}
  
  truncateChars -- 截断字符
  如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。    参数:截断的字符数
  {{ value|truncatechars:9}} #注意:最后那三个省略号也是9个字符里面的,也就是这个9截断出来的是6个字符+3个省略号。
  
  truncateWords -- 截断单词
  在一定数量的字后截断字符串,是截多少个单词。
    例如:‘hello girl hi baby yue ma’,
    {{ value|truncatewords:3}}  #上面例子得到的结果是 'hello girl h1...'
      
    cut -- 移除元素
    移除value中所有的与给出的变量相同的字符串
    {{ value|cut:' ' }}
    
    join -- 拼接
    使用字符串连接列表,就像Python的str.join(list)
    {{ list|join:', ' }}

Tags Tags

Tag looks like this: {% tag %}. Tag is more complex than a variable: some additional information creating in the output text, a number or to control flow through the logic loop, some variables will be used to load subsequent to the template. Some tags require the start and end tags (e.g., {% tag %} ...tag content ... {% endtag%}).

for labels

Through each element: write for, and then automatically generate the tab key structure for the cycle, the cycle is very basic, so simple use, there is no break and the like, complex functions, you have to pass js

Traversing a list

{% for person in person_list %}
    <p>{{ person.name }}</p>  <!--凡是变量都要用两个大括号括起来-->
{% endfor %}

You can use {% for obj in list reversed %}reverse cycle to complete.

Traversing a dictionary:

{% for key,value in d1.items %} 
    {{ forloop.counter }}
      <li>{{ key }} -- {{ value }}</li>
{% endfor %}

Other methods for loop

forloop.counter            当前循环的索引值(从1开始),forloop是循环器,通过点来使用功能
forloop.counter0           当前循环的索引值(从0开始)
forloop.revcounter         当前循环的倒序索引值(从1开始)
forloop.revcounter0        当前循环的倒序索引值(从0开始)
forloop.first              当前循环是不是第一次循环(布尔值)
forloop.last               当前循环是不是最后一次循环(布尔值)
forloop.parentloop         本层循环的外层循环的对象,再通过上面的几个属性来显示外层循环的计数等

Examples of other methods

示例
    {#  {% for key,value in d1.items %}#}
    {#    {{ forloop.counter }}#}
    {#      <li>{{ key }} -- {{ value }}</li>#}
    {#  {% endfor %}#}

    {#    {% for key,value in d1.items %}#}
    {#    {{ forloop.counter0 }}#}
    {#      <li>{{ key }} -- {{ value }}</li>#}
    {#  {% endfor %}#}

    {#    {% for key,value in d1.items %}#}
    {#      {{ forloop.revcounter }}#}
    {#        <li>{{ key }} -- {{ value }}</li>#}
    {#    {% endfor %}#}

    {#      {% for key,value in d1.items %}#}
    {#        {{ forloop.revcounter0 }}#}
    {#          <li>{{ key }} -- {{ value }}</li>#}
    {#      {% endfor %}#}

    {#      {% for key,value in d1.items %}#}
    {#        {{ forloop.first }}#}
    {#          <li>{{ key }} -- {{ value }}</li>#}
    {#      {% endfor %}#}


    <!-- forloop.parentloop示例 -->
    {#<ul>#}
    {#    {% for dd2 in d2 %}#}
    {#      <li>#}
    {#        {% for ddd2 in dd2 %}#}
    {#          {{ forloop.parentloop.counter }}#}
    {#          {{ forloop.counter }}#}
    {#          <a href="">{{ ddd2 }}</a>#}
    {#        {% endfor %}#}
    {##}
    {#      </li>#}
    {#  {% endfor %}#}
    {#</ul>#}

    <!-- empty示例 -->
    {#<ul>#}
    {#   {% for foo in d3 %}#}
    {#       <li>{{ foo }}</li>#}
    {#   {% empty %}#}
    {#     <li>查询的内容啥也没有</li>#}
    {#  {% endfor %}#}
    {##}
    {#</ul>#}

for … empty

forLabel with an optional {% empty %}clause set forth in order to empty or is not found, the operation may be.

{% for person in person_list %}
    <p>{{ person.name }}</p>

{% empty %}
    <p>sorry,no person here</p>
{% endfor %}

if the label

{% if %}Have a variable evaluation, if its value is "True" (exists, is not empty, and not false boolean value type), the block will output the corresponding content.

{% if num > 100 or num < 0 %}
    <p>无效</p>  <!--不满足条件,不会生成这个标签-->
{% elif num > 80 and num < 100 %}
    <p>优秀</p>
{% else %}  <!--也是在if标签结构里面的-->
    <p>凑活吧</p>
{% endif %}

There may be only if and else

{% if user_list|length > 5 %}  <!--结合过滤器来使用-->
  七座豪华SUV
{% else %}
    黄包车
{% endif %}

if statement supports and, or, ==,>, <,! =, <=,> =, in, not in, is, is not to judge, pay attention to the conditions on both sides spaces.

with label

Do not add spaces around the equal sign

{% with total=business.employees.count %}
    {{ total }} <!--只能在with语句体内用-->
{% endwith %}
        或
{% with business.employees.count as total %}
    {{ total }}
{% endwith %}

csrf_token label

When we submit the form to post way, will complain, remember that we are inside the middleware configuration settings inside the csrf a defense mechanism to write-off the ah, itself should not be written off, but should learn how to use it, and do not to make their operation is forbiden, be able to get through this thing.
    This label is used to cross-site request forgery protection, in the form of form pages inside (note the form in which form) on any position to write {% csrf_token%}, this thing when rendering templates replaced with hidden, this label value is a random string, when submitted, this thing has also been submitted, the first thing is our back-end rendering time to add a page, then when you submit data via a form I will give you a form, you take the contents of this I have known you, not with, I forbid you, because we django also kept the background of this thing, and a value of the same value you can do the corresponding verification is not I give you a token, this store what values we later learn, you first know you will do, just like one of us back to this a pass user, if you users do not have to post as I give you the normal page submission form data, or you do not I go to this landing page request, but the request to submit data directly to analog, then I can tell you that the request is illegal Anti-reptile or a malicious attack on my website, after the middleware we elaborate in this thing, but now you have to understand how it happened, understand why django will add this set of defense.

Sending a post request crawler simple simulation:

import requests

res = requests.post('http://127.0.0.1:8000/login/',data={
    'username':'chao',
    'password':'123'
})

print(res.text)

Note

{# ... #}

Precautions

1. Django的模板语言不支持连续判断,即不支持以下写法:
{% if a > b > c %}
...
{% endif %}
2. Django的模板语言中属性的优先级大于方法(了解)
def xx(request):
    d = {"a": 1, "b": 2, "c": 3, "items": "100"}
    return render(request, "xx.html", {"data": d})

Template inheritance

Django template engine is the most powerful and most complex part of the template is inherited. Template inheritance allows you to create a basic "skeleton" template that contains all the elements of your site, and you can define templates quilt blocks can covered.

Easy to understand template inheritance

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{%/span> endblock %}</title>
</head>

<body>
    <div id="sidebar">
        {% block sidebar %}
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
        </ul>
        {% endblock %}
    </div>

    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

 This template, we call it base.html, it defines a simple HTML skeleton can be used in a two page layout. "Sub template" work with their contents fill the empty blocks.

 In this example, blockthe tag may define three content-filled quilt template block. blockTell template engine: child template may override the templates in these locations.

 Child template might look like this:

{% extends "base.html" %}
 
{% block title %}My amazing blog{% endblock %}
 
{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}

extendsTag is the key here. It tells the template engine that this template "inherited" another template. When the system processes the stencil template, firstly, it will locate the parent template - in this case, is "base.html".

那时,模版引擎将注意到 `base.html` 中的三个 `block` 标签,并用子模版中的内容来替换这些block。根据 `blog_entries` 的值,输出可能看起来是这样的:
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css" />
    <title>My amazing blog</title>
</head>
 
<body>
    <div id="sidebar">
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
        </ul>
    </div>
 
    <div id="content">
        <h2>Entry one</h2>
        <p>This is my first entry.</p>
 
        <h2>Entry two</h2>
        <p>This is my second entry.</p>
    </div>
</body>
</html>

For better readability, you can also give your {% endblock %}tag a name .

{% extends "base.html" %}

钩子:{% block title %}
        xxx
    {% endblock %}
钩子:{% block title %}
        xxx
    {% endblock title %}
    
钩子:{% block title %}
        {{ block.super }}  #显示模板内容
        xxx
    {% endblock title %}

 In large template, this method to help you clearly see what a  {% block %}label is closed.

A plurality of the same name can not be defined in a template blocktag.

Package

The page content may be used, such as navigation, footer information components stored in a separate file and then use where needed, can be introduced anywhere in the file by the following syntax.

{% include 'navbar.html' %}

For example: There is a navigation bar below, nav.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1{
            background-color: red;
            height: 40px;
        }
    </style>
</head>
<body>

<div class="c1">
    <div>
        <a href="">xx</a>
        <a href="">dd</a>
    </div>
</div>

</body>
</html>

Embedded navigation bar of the page, test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% include 'nav.html' %}
<h1>xxxxxxxxxx</h1>
</body>
</html>

The difference between the components and plug-ins

组件是提供某一完整功能的模块,如:编辑器组件,QQ空间提供的关注组件 等。

而插件更倾向封闭某一功能方法的函数。

这两者的区别在 Javascript 里区别很小,组件这个名词用得不多,一般统称插件。

Custom tags and filters

1, INSTALLED_APPS in the current configuration settings in the app, django otherwise unable to find simple_tag custom.

2. Create a module in the app templatetags in (name of the module can only be templatetags)

3, create any .py files, such as: my_tags.py

from django import template
from django.utils.safestring import mark_safe
 
register = template.Library()   #register的名字是固定的,不可改变
 
 
@register.filter
def filter_multi(v1,v2):
    return  v1 * v2

@register.simple_tag  #和自定义filter类似,只不过接收更灵活的参数,没有个数限制。
def simple_tag_multi(v1,v2):
    return  v1 * v2

@register.simple_tag
def my_input(id,arg):
    result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
    return mark_safe(result)

my_tags.py before using import from html file defines simple_tag and filter created in

{% load my_tags %} 

Use simple_tag and filter (how to call)

-------------------------------.html
{% load xxx %}  
      
# num=12
{{ num|filter_multi:2 }} #24
 
{{ num|filter_multi:"[22,333,4444]" }}
 
{% simple_tag_multi 2 5 %}  参数不限,但不能放在if for语句中
{% simple_tag_multi num 5 %}

Note: filter can be used in later if, for other statements, simple_tag not

{% if num|filter_multi:30 > 100 %}
    {{ num|filter_multi:30 }}
{% endif %}

day(57)

自定义过滤器

1. app应用文件夹中创建一个templatetags文件件,必须是这个名字
2. templatetags文件夹中创建一个 xx.py文件,文件名字随便起

3. 创建自定义过滤器
    from django import template

    register = template.Library()  #register固定的名字,注册器

    # @register.filter
    # def oo(v1,v2):  #不带参数的过滤器
    #     s = v1 + 'xxoo'

    #     return s

    @register.filter
    def oo(v1,v2):  #带参数的过滤器
        s = v1 + v2
        return s
    
4. 使用  html文件中  {% load 文件名 %} 
     {% load xx %}
    {{ values|oo }} -- 无参数
    {{ values|oo:'asdf' }} -- 有参数

5. 注意:参数最多两个


自定义标签
1. app应用文件夹中创建一个templatetags文件件,必须是这个名字
2. templatetags文件夹中创建一个 xx.py文件,文件名字随便起
3. 创建自定义标签
    @register.simple_tag
    def mytag(v1,v2,v3):  
        s = v1 + '和B哥' + v2 + v3
        return s

4.使用
    {% load xx %}
    {% mytag s1 '和相玺' '和大壮' %}  
5. #可以传多个参数

inclusion_tag

Multi html code segment for returning

1. app应用文件夹中创建一个templatetags文件件,必须是这个名字
2. templatetags文件夹中创建一个 xx.py文件,文件名字随便起
3. 创建自定义inclusion_tag
    @register.inclusion_tag('inclusiontag.html')
    def func(v1):
            return {'oo':v1}

4. func的return数据,传给了inclusiontag.html,作为模板渲染的数据,将inclusiontag.html渲染好之后,作为一个组件,生成到调用这个func的地方
5. 使用
    {% load xx %}
    {% func l1 %}

templatetags/my_inclusion.py

from django import template

register = template.Library()


@register.inclusion_tag('result.html')  #将result.html里面的内容用下面函数的返回值渲染,然后作为一个组件一样,加载到使用这个函数的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}#这里可以穿多个值,和render的感觉是一样的{'data1':data1,'data2':data2....}

templates/snippets/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 inclusion_tag_test %}

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

Static related files

 js, css, img and so is called a static file, then the configuration on django static files, we need to write the configuration file settings in which to write the contents on this:

1 在项目中创建一个文件夹,比如叫jingtaiwenjian

# STATIC_URL = '/xxx/' #别名,随便写名字,但是如果你改名字,别忘了前面页面里面如果你是通过/xxx/bootstrap.css的时候,如果这里的别名你改成了/static/的话,你前端页面的路径要改成/static/bootstrap.css。所以我们都是用下面的load static的方式来使用静态文件路径
2 STATIC_URL = '/static/' #别名

3 STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'jingtaiwenjian'), #注意别忘了写逗号,第二个参数就是项目中你存放静态文件的文件夹名称
]

Directory: Alias ​​is a safety mechanism on the browser via the commissioning stage you can see is the alias name, so that others can not know the name of your static folder, or else someone else will be able to attack through this folder path.

  img

Front page introduction written static files, since aliases may also be modified, so use the time to find a path through the alias load static, to obtain a static file path by way of an alias mapping

img

{% static %}

{% 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>

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

Guess you like

Origin www.cnblogs.com/shuai-jie/p/11228328.html