47, django project (template)


47.1, django template system description:

1, Description:

We can be hard-coded into the HTML code view in python directly, although this technique is easy to explain how the work of view, but it is not a good idea.

def current_datetime(request):

now = datetime.datetime.now()

html = "<html><body>It is now %s.</body></html>" %now

return HttpResponse(html)

Any changes to the page design must make the appropriate changes to the Python code. Site design changes tend to be more frequent than change the underlying Python code

Much, so if you can not make changes in the design of the case Python code changes, it will be much more convenient. Python code written in HTML and design are two

Different items of work, and most professional Web development environments will assign them to different people and even different parts of the door to complete. Designers and HTML / CSS compilation

Code personnel should not be required to edit Python code to get their job done. Write Python code templates programmers and designers to make two tasks at the same time

Efficiency is the highest, far better than to let a person waiting for the other to finish editing work on a file that contains both Python and HTML are included. Based on these

The reason, the page design and code separation Python is much cleaner and easier to maintain. We can use the Django template system Template System

To implement this pattern.


2, the template consists of:

HTML code of logical control code


47.2, the logic control code consists of:

1, the variable (using curly brackets reference variables):

(1) syntax:

{{ var_name }}


(2) to pass parameters to the template .html files view function:

1)views.py:

def current_time(request):

now=datetime.datetime.now()

return render(request, 'current_datetime.html', {'current_date':now})

2)current_datetime.html:

{{ current_date }}


(3) variable-depth look, universal character of the period:

Template system capable of handling more complex data structure is very simple, for example list, dictionary and custom objects.

Key traversing complex data structures in Django templates is the dot character (.).


(4) The variable filter, filter using:

1) syntax:

{{ obj|filter:param }}

2) parameters:

add: adding a value corresponding to the variable

addslashes: former variable quotes to slash

capfirst: capitalize the first letter

cut: Remove the specified characters from a string

date: Date Format String

default: If the value is False replaces the default value to a set, otherwise use the original value

default_if_none: If the value is None, to replace the default values ​​to be provided, otherwise use the original value

3) Example:

A、

value1="aBcDe"

{{ value1|upper }}

#ABCDE

B、

value2=5

{{ value2|add:"3" }}

#8

C、

value3='he llo wo r ld'

{{ value3|cut:' ' }}

#helloworld

D、

import datetime

value4=datetime.datetime.now()

{{Value4 | Date: 'Ymd'}}

#2019-12-25

E、

value5=[]

{{Value5 | default: 'Empty'}}

# Empty

F、

value6='<a href="#">跳转</a>'

{{ value6 }}

#<a href="#">跳转</a>


{% autoescape off %}

{{ value6 }}

{% endautoescape %}

#跳转(是一个 302 重定向超链接)


{{ value6|safe }}

#跳转(是一个 302 重定向超链接)


{{ value6|striptags }}

#跳转(字符串)

G、

value7='1234'

{{ value7|filesizeformat }}

#1.2 KB


{{ value7|first }}

#1


{{ value7|length }}

#4


{{ value7|slice:"::-1" }}

#4321


{{ value7|slice:"3" }}

#123


{{ value7|slice:"-3" }}

#1

H、

value8='http://www.baidu.com/?a=1&b=3'

{{ value8|urlencode }}

http%3A//www.baidu.com/%3Fa%3D1%26b%3D3

I、

value9='hello I am lc'

{{ value9|truncatechars:'10' }}

#hello I a…


{{ value9|truncatewords:'2' }}

#hello I …


2、标签tag的使用(使用大括号和百分比的组合来表示):

(1)语法格式:

{% tags %}


(2){% if %} 的使用:

1)说明:

{% if %} 标签计算一个变量值,如果是“true”,即它存在、不为空并且不是false的boolean值,系统则会显示{% if %}和{% endif %}间的所有内容

{% if %} 标签接受and,or或者not来测试多个变量值或者否定一个给定的变量。

{% if %} 标签不允许同一标签里同时出现and和or,否则逻辑容易产生歧义,例如下面的标签是不合法的:

{% if obj1 and obj2 or obj3 %}

2)示例:

{% if num >= 100 %}


{% if num > 200 %}

<p>num大于200</p>

{% else %}

<p>num大于100小于200</p>

{% endif %}


{% elif num < 100 %}

<p>num小于100</p>


{% else %}

<p>num等于100</p>


{% endif %}


(3){% for %} 的使用:

1)说明:

{% for %}标签允许你按顺序遍历一个序列中的各个元素,每次循环模板系统都会渲染{% for %}和{% endfor %}之间的所有内容。

2)代码:

<ul>

{% for obj in list %}

<li>{{ obj.name }}</li>

{% endfor %}

</ul>

提示:在标签里添加reversed来反序循环列表,{% for obj in list reversed %}


(4){% csrf_token %} 的使用:

1)说明:

用于生成csrf_token的标签,用于防治跨站攻击验证。注意如果你在view的index里用的是render_to_response方法,不会

生效,其实这里是会生成一个input标签,和其他表单标签一起提交给后台的。

2)代码:

<form action="" method="post">

{% csrf_token %}

......

</form>


(5){% url %} 的使用:

1)说明:

引用路由配置的地址,用于路由配置别名。

2)代码:

<form action="{% url "bieming"%}" method=""post>

<input type="text">

<input type="submit" value="提交">

{%csrf_token%}

</form>


(6){% with %} 的使用:

1)说明:

用更简单的变量名替代更复杂的变量名。

2)代码:

{% with total=fhjsaldfhjsdfhlasdfhljsdal %} {{ total }} {% endwith %}


(7){% verbatim %} 的使用:

1)说明:

禁止render。

2)代码:

{% verbatim %}

{{ hello }}

{% endverbatim %}


(8){% load %} 的使用:

1)说明:

加载标签库。

2)代码:

<head>

<meta charset="UTF-8">

<title>Title</title>

{% load staticfiles %}

</head>

<script type="text/javascript" src={% static "jquery-3.1.1.js" %}></script>


(9){% comment %} 的使用:

1)说明:

用于模板代码的多行注释,其中单行注释为 {# <要注释的内容> #}。

2)代码:

{% comment %}

......

{% endcomment %}


(10)补充:

filter可以用在if等语句之后,类如下代码:

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

{{ num|filter_multi:30 }}

{% endif %}


3、extend模板继承:

(1)说明:

本质上来说,模板继承就是先构造一个基础框架模板,而后在其子模板中对它所包含站点公用部分和定义块进行重载。

你可以对那些不同的代码段进行定义,而不是共同代码段。


(2)代码:

1)第一步:

定义基础模板base.html文件保存到template目录下,该框架之后将由子模板所继承。base.html 的模板定义了一个简

单的 HTML 框架文档,我们将在本站点的所有页面中使用。 子模板的作用就是重载、添加或保留那些块的内容。我 们

使用模板标签 {% block %},所有的 {% block %} 标签所要做的是告诉模板引擎,该模板下的这一块内容将有可能被子

模板覆盖。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<html lang="en">

<head>

<title>{% block title %}{% endblock %}</title>

</head>

<body>

<h1>My helpful timestamp site</h1>

{% block content %}{% endblock %}

{% block footer %}

<hr>

<p>Thanks for visiting my site</p>

{% endblock %}

</body>

</html>

2)第二步:

继承模板。

{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}

<p>It is now {{ current_date }} </p>

{% endblock %}

继承模板后得到的结果为:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<html lang="en">

<head>

<title>The current time</title>

</head>

<body>

<h1>My helpful timestamp site</h1>

<p>It is now {{ current_date }}</p>

<hr>

<p>Thanks for visiting my site</p>

</body>

</html>


(3)模板继承注意事项:

1)如果在模板中使用 {% extends %} ,必须保证其为模板中的第一个模板标记。 否则,模板继承将不起作用。

2)一般来说,基础模板中的 {% block %} 标签越多越好。 记住,子模板不必定义父模板中所有的代码块,因

此你可以用合理的缺省值对一些代码块进行填充,然后只对子模板所需的代码块进行(重)定义。 俗话说,钩

子越多越好。

3)如果发觉自己在多个模板之间拷贝代码,你应该考虑将该代码段放置到父模板的某个 {% block %} 中。如果

你需要访问父模板中的块的内容,使用 {{ block.super }} 这个标签,这一个魔法变量将会表现出父模板中的内

容。如果只想在上级代码块基础上添加内容,而不是全部重载,该变量就显得非常有用了。

{% block test.super %}

<只会显示父模板中的内容,即使这里写了内容也不会覆盖父模板中的内容>

{% endblock %}

4)不允许在同一个模板中定义多个同名的 {% block %} 。 存在这样的限制是因为 block 标签的工作方式是双

向的。也就是说,block 标签不仅挖了一个要填的坑,也定义了在父模板中这个坑所填充的内容。如果模板中

出现了两个相同名称的 {% block %} 标签,父模板将无从得知要使用哪个块的内容。















Guess you like

Origin www.cnblogs.com/LiuChang-blog/p/12320671.html