04.Django Basic Four of the template system

A grammar

  Template rendering of official documents

  

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

  {{ }}with{% %}

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

Bivariate

  

  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).

  A few examples:

  view 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>
注意:
    调用对象里面的方法的时候,不需要写括号来执行,并且只能执行不需要传参数的方法,如果你的这个方法需要传参数,那么模板语言不支持,不能帮你渲染

  Note that we use the template grammar directly js code when there will be a template escape when rendering operation, will be s = [ 'ha', 'xx'] quoted elements the data becomes a special symbol :

    <script>
        // 不加safe的话,引号会被转义。        // var a = {{ s }}
        // var a = [&#39;哈哈&#39;, &#39;xx&#39;];
        // console.log(a[0])
        // 加上safe就正常了
        var a = {{ s|safe }};
        console.log(a[0])        // 还要注意,当我们模板渲染的时候,后端返回的数据是字符串的话,我们需要将{{ s }}外面加上引号        比如s = '哈哈'        js中的写法        var a = '{{ s }}'
    </script>    

Three filters

  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

  Django template language provides about sixty built-in filter.

default

    If a variable is false or empty, the default values ​​given. Otherwise, use the value of the variable.

{{ value|default:"nothing"}}

    If value is null or the value is not passed, then nothing is displayed

length

    Returns the length, acting on the string and the value list.

    {{ value|length }}

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

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.

slice

    Slice, if the value = "hello world", as well as other types of data slice

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

date

    Formatting, if value = datetime.datetime.now ()

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

  Parameters available on the date and time (except Y, m, d, etc.) there are many, are interested can look to look.

  

safe

    Django template during the template when rendering HTML tags will be syntactic and JS tags automatically escaped, for obvious reasons, this is for security, django worried that this data is added by the user, for example, if someone gives you time to write reviews some js code, the review a submission, js code will execute you, so that you are not able to carry out some of the bad child, write a pop cycle of death, and that the browser can use it, is not it will always pop ah this is called xss attack, so the browser will not let you do so, you escaped. 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.

    We went to the local network to see, to see the results after the browser is rendering, you can see through that part of the response of the network. This is a special symbol tag all wrapped up, not a label, it is django do a thing.

    img

    such as:

      value = " point I " and value = ""

{{ value|safe}}

    Many sites, will be on content submitted by you to filter some sensitive words, special characters, labels, pornography, gambling vocabulary and so on, as you submit content, other people will detect the contents of your submission, if you include these terms, do not let you submit, in fact, this is the fundamental way to solve xss attacks, such as blog garden:

    img

truncatechars

    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 ( "...").

    Parameters: the number of characters truncated

{{ value|truncatechars:9}} #注意:最后那三个省略号也是9个字符里面的,也就是这个9截断出来的是6个字符+3个省略号,有人会说,怎么展开啊,配合前端的点击事件就行啦

truncatewords

    Truncates the string after a certain number of words, how many words are cut.

    Rei如: 'hello girl hi baby yue ma',

{{ value|truncatewords:3}}  #上面例子得到的结果是 'hello girl h1...'

cut

    Removing all variable value given the same string

{{ value|cut:' ' }}

    If value is 'i love you', then the output 'iloveyou'.

join

    String connection list, {{list | join: ','}}, as a Python str.join (list)

timesince (understand)

    The date format to time since that date (e.g., "4 days, 6 hours") self.

    Optional use of a variable parameter, which is used as a point of comparison date included (without parameters, as a comparison point is now). For example, if the date is an example of blog_date June 2006 midnight on the 1st, the date and comment_date instance, 2006 at 8:00 on June 1, the following will return "8 hours":

{{ blog_date|timesince:comment_date }}

    Min is the smallest unit used for any date in the future with respect to the comparison point, it will return "0 minutes."

timeuntil (understand)

    Similar to timesince, except that it measures the time from now on until a given date or date and time. For example, if today is June 1, 2006, and conference_date instance is reserved date June 29, 2006, the {{conference_date | timeuntil}} will return to "four weeks."

    Use of optional parameters, which is used as a comparison point comprising date (rather than the current) variable. If from_date contains 2006 June 22, the following will return "a week":

{{ conference_date|timeuntil:from_date }}

  Here are some simple common filter templates, more detailed

Four labels 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

{% 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,val in dic.items %}
    <p>{{ key }}:{{ val }}</p>
{% endfor %}

    NOTE: cycle number can be displayed {{forloop}}, must be used inside the loop  

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

    img

    img

    

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

Of course, 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

    Use a simple name cache a complex variable, used to a complex variable aliases, when you need to use an "expensive" method (such as database access) many times when it is very useful

    E.g:

    Note that no space around the equal sign.

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

    or

{% with business.employees.count as total %}
    {{ total }}
{% endwith %}

csrf_token

    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 tag is used CSRF protection,

    In the form of which form page (note that the form in which form) on any position to write {% csrf_token%}, this thing when rendering templates replaced with the hidden value of this tag is a random string, when submitted, this thing has also been submitted, the first thing is the back-end rendering when we add to the page, then when you submit data via a form I'll give you a form, you take the content I've known you, without , I will forbid you, because the background we django also exist with this thing, and a same value you this value, you can do the corresponding verification is not I give you a token, to store the value of the things we later learn, you first I know on the line, just like the one we give the user a backstage pass, if you follow my users do not have to post this to your normal page submission form data, or that you did not ask me to go to this landing page, but direct simulation request to submit the data, then I can tell you that the request is illegal, anti-reptile or a malicious attack on my website, Middleware later when we go into detail 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 template language does not support continuous judgment that does not support the following wording:
{% if a > b > c %}
...
{% endif %}
  1. Django template language's priority attribute is greater than the method (understand)
def xx(request):
    d = {"a": 1, "b": 2, "c": 3, "items": "100"}
    return render(request, "xx.html", {"data": d})

      As above, when we use 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.

Five 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.

  By starting from the following example, it is 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".

  At that time, the template engine will notice base.htmlthe three blocklabels, and with the contents of the sub-template to replace the block. The blog_entriesvalue of the output may look like this:

<!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> 

  Please note that the child template does not define the sidebarblock, so the system uses the value of the parent template. Parent template {% block %}Content tab is always used as an alternative content (fallback).

  This provides the greatest degree of code reuse, and that add content to the shared content area more simple, e.g., in the range of the navigation portion.

  Here are some tips for using inheritance:

  • If you use the template {% extends %}label, it must be the first template tag. Under any other circumstances, template inheritance will not work, when rendering templates django do not know what you're doing.
  • Set in the more base templates {% block %}, the better label. Remember, child templates do not have to define all parent blocks of templates, so you can fill in most reasonable default content blocks, and then, only the definition that the one you need. Hook a little bit more is better than less good.
  • If you find yourself duplicating content in a large number of templates, it probably means you should move the contents to the parent of a template {% block %}in.
  • If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using {{ block.super }} will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template. 将子页面的内容和继承的母版中block里面的内容同时保留

      img

  • For better readability, you can also give your {% endblock %}tag a name . E.g:
{% block content %}
...
{% endblock content %}  

  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.

6-pack

  

  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 simple components and plug-ins

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

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

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

Seven custom tags and filters

  When we use these later revisit:

1、

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

2、

Creating templatetags module app 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)

4、

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

{% load my_tags %} 

5、

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

inclusion_tag

    Multi html code segment for returning

    Example:

      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>

Eight static files related

  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:

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

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

Note that a html file a written question to consider when relative path:

example:

<form action="/login/"></form>
<img src="/static/1.jpg" alt="">
等标签需要写路径的地方,如果写的是相对路径,那么前置的/这个斜杠必须写上,不然这个请求会拼接当前网页的路径来发送请求,就不能匹配我们的后端路径了

Guess you like

Origin www.cnblogs.com/changxin7/p/11571672.html