Django's template layer

Template layer

Django templates are some of the text string, the role is to separate performance document and data area. Template defines placeholders and basic logic (template label), specify how to display the document. Typically, the template is used to generate HTML, but Django templates can generate any text-based format.

There are two back-end transfer of data using the Django template way toward the front page:

第一种:以字典的形式传递数据
name = 'linwow'
return render(request,'index.html',{'name':name})

第二种:只能用在键和值的变量名相同的情况下,且会导入所以变量,即使不需要用到的也会被导入
name = 'linwow'
password = '123'
return render(request,'index.html',locals()) 

Elegant template system can deal with a lot of complex data structures, such as lists, dictionaries, and custom objects. Key traversing complex data structures in Django templates is the dot (.). Number Index can access dictionary keys, attributes, methods, or object point.

view.py:
import datetime
def index(request):
    string = "hello linwow!"  # 字符串
    mylist = [111, 222, 333]  # 列表
    mydict = {"name": "linwow", "password": 123}  # 字典
    mydate = datetime.date(1999, 12, 30)  # 日期对象
    def func():
        return '你调用了我?'
    class Person(object):
        def __init__(self, name):
            self.name = name
        def func(self):
            return self.name
        @classmethod
        def index(cls):
            return 'cls'
        @staticmethod
        def bar(name, age):
            return 'bar'
    obj = Person("linwow")  # 自定义类对象
    return render(request, "index.html",locals())
    
index.html:
<p>我是传过来的字符串>>>{{string}}</p>
<p>我是传过来的列表>>>{{ mylist }}</p>
<p>我是传过来的列表中的索引2>>>{{ mylist.2 }}</p>
<p>我是传过来的字典>>>{{ mydict.name }}</p>
<p>我是传过来的日期>>>{{ mydate.year }}</p>
<p>我是传过来的函数>>>{{ func }}</p> # 后端传函数名到前端,会自动加括号调用,但是不支持传参
<p>我是传过来的类对象>>>{{ obj.name }}</p> # 后端传对象到前端,就相当于打印了这个对象
<p>我是传过来的类对象的类方法>>>{{ obj.index }}</p>
<p>我是传过来的类对象的静态方法>>>{{ obj.bar }}</p>

Notes : will not show to front page

{#调用python自带的内置方法,可以调用不需要传参的一些内置方法#}

filter

Template filter is a simple way to adjust the value of the variable before displaying variable. Filter pipe symbol specified, the following
is shown:

{{ name|lower}}

The code is adjusted by the first lower filter {{name}} variable value - to convert to lower case text, and then displayed. Filters can be connected in series, i.e. the output of a filter is passed to the next filter.

The following example obtains the first element of the list, then convert to uppercase:

{{ my_list|first|upper}}

Some filters can accept parameters. After the filter parameters on the colon, always in double quotes. E.g:

{{ bio|truncatewords:"30"}}

The example above shows the first 30 words of the bio variable.

Here are a few of the most important filters:

  • addslashes: a backslash, single quotes and a backslash before the quotes. String can be used to escape. For example: {{val-ue | addslashes}}.
  • date: The format string formatted date or datetime objects parameters (do not add percent sign). For example: {{ctime | date: 'Ym-d'}}.
  • length: length of the return value. List, it returns the number of elements. String, it returns the number of characters. If the variable is not defined, it returns 0.
  • add the parameter added to the value. For example: {{value | add: "2"}} if the value is 4, the output 6.
  • If the default value is false, the specified default value; otherwise, the value of value. For example: {{value | default: "nothing"}}
  • Dictsort list specified by the parameters constituted dictionary sorted key, returns a sorted list. For example: {{value | dictsort: "name"}}
  • filesizeformat the value formatted as a human-readable file size (e.g. '13 KB ',' 4.1 MB ',' 102 bytes', etc.). For example: {{value | filesizeformat}} If the value is 123456789, the output of 117.7 MB.
  • first returns the first element in the list.
  • last Returns the last element in the list.
  • If the length is equal to the value of the parameter length_is returns True, otherwise return False. For example: {{value | length_is: "4"}}
  • safe escape without further HTML tag string prior to output. This automatically closing the escape filter has no effect.
  • slice returns slice of the list. Like Python slice syntax of the list.
  • Truncated exceeds the specified length of the string truncatechars string. String truncated (...) ending with an ellipsis translatable. For example: {{value | truncatechars: 9}}
  • truncatewords truncates the string after the specified number of words, according to the space taken text.

Emphasize:

前后端取消转义
前端:
	|safe
后端:
	from django.utils.safestring import mark_safe
	xxx = mark_safe('<h1>我是h1标签</h1>')

label

if/else

{% If%} value calculation variable, if the content is true (i.e. the presence, not null, not false value), the system displays the template {% if%} and {% endif%} between. E.g:

{% if today_is_weekend%}
<p>Welcome to the weekend!</p>
{% endif%}

{% Else%} tags are optional:

{% if today_is_weekend%}
<p>Welcome to the weekend!</p>
{% else%}
<p>Get back to work.</p>
{% endif%}

if label may also have one or more {% elif%} clause:

{% if athlete_list%}
Number of athletes:{{ athlete_list|length}}
{% elif athlete_in_locker_room_list%}
<p>Athletes should be out of the locker room soon!</p>
{% elif...
...
{% else%}
<p>No athletes.</p>
{% endif%}

{% If%} supports and, or not tested or more variables, or taking anti-specified variable. In the same tag and can be used simultaneously and or, at this time, and a higher priority than or. If you need parentheses indicate the priority should be to use nested if tags. Sequential use parentheses control operation is not supported. If you feel the need to use parentheses, consider performing logic outside the template, and then pass the results through a special template variables. Alternatively, the direct use of nested {% if%} tag.

for

{% For%} tags for each element of a sequence of iterations. At each iteration, the template system will render the contents between {% for%} and {% endfor%} of. {% For%} tags can be nested.

<ul>
{% for athlete in athlete_list%}
<li>{{athlete.name}}</li>
{% endfor%}
</ul>

Add reversed in the label, reverse iterator list:

{% for athlete in athlete_list reversed %}
...
{% endfor %}

{{% Empty%}}: When your object is empty for loop automatically when walking {{% empty%}} pieces of content code

book_list=[]

{% for foo in book_list %}
    {{ foo.name }}
    {% empty %}
        <p>你给我的容器类型是个空啊,无法for循环</p>
{% endfor %}

Before the end of the cycle, can not "jump." If you need to do this, change the variable to iterate, containing only the desired value iteration. Similarly, no "continue" statement can not return immediately to the beginning of the loop. {% For%} In the inner loop, the template can be accessed in a variable named forloop. This variable has a few attributes, you can learn some of the information circulating through their process:

  • Forloop.counter value is an integer, denotes the number of cycles. The value of this attribute from the beginning, so the first time through the loop, forloop.counter equal to 1.
  • Forloop.revcounter is an integer value representing the number of elements in the remaining cycles. The first time through the loop, the value for-loop.revcounter the total number of elements in the sequence to traverse. When the last cycle, forloop.revcounter a value of 1.
  • forloop.revcounter0 and forloop.revcounter similar, but the index is zero-based. The first time through the loop, the value for-loop.revcounter0 the number of elements in the sequence minus one. When the last cycle, forloop.revcounter0 value of zero.
  • forloop.first is a Boolean value, the first time through the loop to True.
  • forloop.last is a Boolean value, the last time through the loop to True.

forloop tags are only available inside the loop. When the template parser encounters {% endfor%}, forloop disappear.

Django provides {% ifequal%} tag. {% Ifequal%} tag compares two values, if they are equal, the display content between the {% endifequal%} and {% ifequal%}.

Create a template library

Whether custom tags or filters, the first thing is to create a template library. You must do three things when creating a template library:

  • In the name of the application to create a new folder named templatetags (must be that name).
  • Templatetags create two empty files in the directory: __ init __ py (Python that this is a package containing Python code) and store custom label (filter) files, the latter is the name used to load label.
  • A valid tag library module layer must register the named variable, which value is an instance of template.Library. Tags and filters are registered in this way. Thus, the module to be inserted at the top of the following codes:
from django import template
register = template.Library()	

For example, a custom label (filter) in my_tag.py save the file, then to be so loaded in the template:

{% load my_tag%}

{% Load%} statement loads is specified Python module, rather than the application.

Custom filter

my_tag.py:
@register.filter(name='myadd')
def index(a,b):
	return a+b
	
index.html:
{% load my_tag %}
{{ 666|myadd:8 }}

Custom label

my_tag.py:
@register.simple_tag
def plus(a,b,c):
	return a+b+c

index.html
{% load my_tag %}
{% plus 1 2 3 %}

Custom inclusion_tag

my_tag.py:
@register.inclusion_tag('login.html',name='login')
    def login(n):
    	l = [ '第%s项'%i for i in range(n)]
    	return {'l':l}
    	
login.html:
<ul>
	{% for foo in l %}
	<li>{{ foo }}</li>
	{% endfor %}
</ul>

index.html
{% load my_tag %}
{% login 5 %}

Inheritance and import templates

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.

First of all need to be divided in multiple regions inherited template

{% block 给区域起的名字 %}
	...
{% endblock %}

Normally a template should have at least three

{% block css %}
	页面css代码块
{% endblock %}

{% block js %}
	页面js代码块
{% endblock %}

{% block content %}
	页面主体内容
{% endblock %}

Daughter board inherited template

先继承模板所有的内容
{% extends 'home.html' %}
然后根据block块的名字修改指定区域的内容
{% block content %}
	<h1>登录页面</h1>
	<form action="">
	<p>username:<input type="text" class="form-control"></p>
	<p>password:<input type="text" class="form-control"></p>
	<input type="submit" class="btn btn-success">
	</form>
{% endblock %}

extends tag is the key here, it tells the template engine that this template "inherited" another template. When the template system to deal with this template, it will first locate the parent template.

Template Import:

Html module as introducing some way to show another html

{% include '想导入的html文件名' %}

Static configuration file

{% load static %}  

<link rel='stylesheet' href="{% static 'css/mycss.css'%}">  # 第一种方式
<link rel='stylesheet' href="{% get_static_prefix %}css/mycss.css">  # 第二种方式

Django template discovery mechanisms: Django Find template is in the process of looking at each app's templates folder (not just the current app in the code only to find in the current folder in the app templates files). Each time the app templates to form a list of folders, Django walk through the list, one by one folder to find, when found in a folder on a file stops, all are finished to traverse not find the specified template is Template Not Found (a process similar to find Python package). Such design is advantageous course, there are disadvantages, is a favorable place is a app can use the template file to another app, the harm is likely to be the wrong. So when we're using to build a app of the same name in the templates folder, so just fine.

This requires that every app in the templates file folder to build a app name, and the only app associated with the template on app / templates / app / directory,

Guess you like

Origin blog.csdn.net/linwow/article/details/91463078