Django template template

Django template template

Configuration settings

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',
            ],
        },
    },
]

Template syntax

{{ 变量 }}  {% 逻辑 %}

Almighty period No. .

<h1>{{ num }}</h1>
<h1>{{ s }}</h1>
<h1>{{ l1.1 }}</h1>
<h1>{{ d1.number }}</h1>
<h1>{{ a.yue }}</h1>  <!-- 注意,调用方法时不能加括号,所以如果方法带参数就没法用了 -->
<h1>{{ a.xx }}</h1>

views.py Wording

def home(request):

    num = 100
    s = 'hello my girl I love you'
    l1 = [11,22,33]
    d1 = {'name':'冠希哥','number':1000}
    class A:
        balance = 2000
        def __init__(self):
            self.xx = 'oo'
        def yue(self):
            return 'how much!'
    a = A()
    # render({'xx':'oo'})
    return render(request,'home.html',{'num':num,'s':s,'l1':l1,'d1':d1,'a':a})

filter

Filter Usage:

{{ 变量|过滤器名称:'参数' }}

Not all filters have parameters, no parameters, then the wording:

{{ 变量|过滤器名称 }}

Built-in filter

<h1>{{ s|truncatechars:n }}</h1> # 过滤器里面的参数都可以写后端返回的变量

default -- <h1>{{ xx|default:'抱歉,没有数据!!' }}</h1> # 默认值
length  -- <h1>{{ l1|length }}</h1>  # 获取变量数据长度
filesizeformat -- <h2>{{ file_size|filesizeformat }}</h2> # 大小按照人类可读的显示
slice -- <h2>{{ s|slice:'0:7' }}</h2> #切片 顾头不顾腚
date -- <h3>{{ now|date:'Y-m-d H:i:s' }}</h3>  # 日期格式化显示
safe -- <h1>{{ a_tag|safe }}</h1> # 数据:a_tag = "<a href='http://www.baidu.com'>百度</a>"
truncatechars -- <h1>{{ s|truncatechars:'6' }}</h1>   # 如果字符串字符多于指定的字符数量,那么会被截断。可用来截取长文本为一行。
join -- <h1>{{ l1|join:'+' }}</h1>    # 将数组拼接成字符串
safe introduction

Django template during the template when rendering HTML tags will be syntactic and JS tags automatically escaped. For obvious reasons, this is for safety. Django worried that this data is added by the user, for example, if someone gives you some time to write reviews js code. This review a submission, js code execution friends. So 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, 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 separate variable filter we can |safetell Django way the code is safe does not have to be escaped.

label

The for loop label

Example:

<ul>
    {% for i in l1 %}  # 循环列表
        <li>{{ i }}</li>
    {% endfor %}
</ul>

<ul>
    {% for i in l1 reversed %}  # 翻转循环列表时
        <li>{{ i }}</li>
    {% endfor %}
</ul>

<ol>
    {% for key in d1.keys %}  # 循环字典的键
        <li>{{ key }}</li>

    {% endfor %}
    {% for key in d1.values %} # 循环字典的值
        <li>{{ key }}</li>

    {% endfor %}
    {% for key,value in d1.items %} # 循环字典的键值对
{#        {{ forloop.counter }}#}
        <li>{{ forloop.last }}>>>>{{ key }}---{{ value }}</li>
        {% for foo in d1.hobby %}
            {{ forloop.parentloop.counter }}---{{ forloop.counter }}<a href="">{{ foo }}</a>

        {% endfor %}

    {% endfor %}

</ol>

forloop count

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

Determine whether the empty iterator object is empty

{% for i in l1 %} #当没有数据时,会生成empty的内容
    <li>{{ i }}</li>
{% empty %}
    <p>啥数据也没有!</p>
{% endfor %}

if the label

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

Single condition is determined
{% if num == 11 %}
    <a href="">详细些</a>
{% else %}
    <p>hahahhahah</p>
{% endif %}
Multi-conditional
{% if num > 100 or num < 0 %}
    <p>无效</p>  <!--不满足条件,不会生成这个标签-->
{% elif num > 80 and num < 100 %}
    <p>优秀</p>
{% else %}  <!--也是在if标签结构里面的-->
    <p>凑活吧</p>
{% endif %}
Used in conjunction with filtration
{% if user_list|length > 5 %}  <!--结合过滤器来使用-->
七座豪华SUV
{% else %}
黄包车
{% endif %}

with label

<h1>
    {% with l2.1.name as sb  %}  # 给长的数据调用起名字,只能在with标签内部使用
        {{ sb }}  
        <a href="">{{ sb }}</a>
    {% endwith %}
{#    {{ l2.1.name }}#}
</h1>

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

Note that, remember to use the tag endwith closed with the label, and alias only works a pair with the label closed in.

csrf_token authentication mechanism by csrf

When using the Django framework post submission form, it will complain. Remember when we configure the settings inside the middleware inside a csrf defense mechanism to write off. But we really do not log out of it, but should learn how to use it, and let their operation is forbiden. Be able to get through csrf_token label.

This tag is used to prevent cross-site request forgery (Cross-site request forgery, csrf).

In the pages of the form form inside (note the form in which form) written on any position

{% csrf_token %}

Replaced with something to hide this template when rendering <input type="hidden" name="csrfmiddlewaretoken" value="8J4z1wiUEXt0gJSN59dLMnktrXFW0hv7m4d40Mtl37D7vJZfrxLir9L3jSTDjtG8">tag. The value of this tag is a random string. When the form is submitted, this thing has also been submitted. Because this thing is the back end when rendering the page to add, then when you submit data via a form I'll give you a form, you take the content I've known you, not with, I forbid you. Because the background we also kept a django this thing, and you the same value as a value that can be done to verify correspondence is not I give you a token.

Store this stuff values ​​behind us to learn, you know first click on the line, just like one of us back to the users of a passport, if you users do not have to post as I give you the normal page submission form data, or you did not ask me to go to this landing page, but directly simulate a request to submit data, then I can tell you that the request is illegal, anti-reptile or a malicious attack on my website, middleware later when we fine I say this thing, but now you want to understand how, to understand why Django will add this set of defense.

post reptile
import requests

ret = requests.post('http://127.0.0.1:8000/login/', data={
    'uname':'chao',
    'pwd':'123',
})
print(ret.content.decode('utf-8'))

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.

Custom Templates:

<!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, block tag defines the content of the template may be sub-three-filled block. block tells the 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 %}

extends tag 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 block label, and with the contents of the child template to replace the block.

block.super

{% block content %}
    {{ block.super }} # 将模板中的content这个名称的块中的内容拿过来
    菜单1的内容
{% endblock %}

For better readability, you can also give your endblock a tag name . E.g:

{% block content %}
...
{% endblock content %}  

Package

  1. Write a component .htmlfile
  2. In using this component htmlfile, write the following contents
{% include 'zujian.html' %}

Custom tags and filters

  1. Create a folder in the app application templatetagsfolder, the module name onlytemplatetags

  2. Create any .py files, such as:my_tags.py

  3. File write the following, and custom filters (up to two parameters)

    from django import template
    register = template.Library()  #register变量名称必须是它
    @register.filter  
    def oo(v1,v2):
        print(v1)
        return v2 + v1 + 'oo'
  4. Used in html file write the following code

    {% load mytags %}
    <h1>{{ name|oo:'xxxx' }}</h1>
  5. Custom labels, and the process as above, but the decorator changed, but also the use of different

    @register.simple_tag
    def ootag(v1,v2,v3):  #参数没有限制
        print(v1,v2,v3)
        return v1 + 'ootag!!' + v2 + v3
  6. Since the use of custom labels

    {% load mytags %}
    <h1>{% ootag name 'sss' '1111'%}</h1>
  7. inclusion_tag, component tag, see illustration:

    1574154069760

Static configuration file

In the project, js, css, jgp pictures, etc. are known as static files.
In django uses:

  1. Configuration. In settingsthe configuration file and write the following configurations:

    STATIC_URL = '/static/' #127.0.0.1:8000/static/bootstrap/css.
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR,'jingtaiwenjianjia'),    # 文件夹名称尽量不要和别名的名称冲突
    ]
  2. html Used in the file:

    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">

    When a relative path to introduce static files, front slash must be added. Whatever it is, a label is the same, the relative access path must be added in front of the slash.

In addition, we can also create a file called static application sub-folder in the project, the static file into the inside. At this time, no longer settings.pyin any configuration. Compared to the above way, this method is more commonly used. Because the import static files in this way, PyCharm will be operating tips.

When in use, the top of the html page statement to load static files:

{% load static %}

In the tab, you can find our direct static method of static files:

<link rel="stylesheet" href="{% static bootstrap-3.3.7-dist/css/bootstrap.min.css %}">

Written in html file is:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
</head>
<body>

</body>
<script src="{% static 'jquery.js' %}"></script>
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
</html>

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/12521545.html