经过前面两节的讲解,我们现在已经可以通过引入外部的样式对我们的html页面进行装饰了。但是不论我们再如何装饰,发布出来的html也只是个静态的页面。比如我们现在需要每次页面刷新的时间都在页面上展示出来。静态页面的内容都是写死的,那现在我们尝试用动态的的语言来实现我们的功能。


django中实现动态页面需要从两个地方进行处理:

1、应用文件夹app01中的views.py要修改index()函数的内容定义要传给html页面的变量内容

2、在html页面代码中加入jinja格式的动态脚本语言,将index()函数里变量内容引入html页面里(Django实现这个功能其实用的就是jinja2这个包)


先简单介绍一下jinja2的动态语言语法。目前常用的其实就是实现for循环和if else判断了。在python中如果要用for方法遍历一个列表的话,代码如下:

li=[1,2,3]
for i in li:
    print i

如果用jinja实现这个循环列表,那么语法就变成了

{% for i in li %}
    <h1>{{ i }}</h1>
{% endfor %}

因为html没哟print语法,所以输出的时候加了个<h1>标签。

if的python方法就不写了,直接写jinja的语法了

{% if x == 1 %}
    <h1>1234</h1>
{% else %}
    <h1>5678</h1> 
{% endif %}

 从上面的语法可以看出来,其实jinja的判断语句格式python很像。在只是在判断语句两边添加了 {% %} 这个标识。另外在最后的结束的时候还要写上关闭符{% endxx %}。变量用双大括号` i `来包裹。但是不管是列表li还是变量x都是由views.py里的index()传进去的。下面我们来编写一个完整的代码

先修改views.py文件里的index()

views.py

from django.shortcuts import render
import time
# Create your views here.
def index(request):
    # 将获取的当前时间格式化后赋值给now_time
    now_time = time.strftime('%Y-%m-%d %H:%M:%S')
    # 建立一个字典,将要传给html的变量作为key值,变量的内容作为value值
    index_dic = {
        'li': ['haha', 'hehe', 'heihei'],
        'x': 2,
        'now': now_time
               }
    # 将字典导入render方法
    return render(request, 'index.html', index_dic)

在修改templates目录下index.html文件

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.5-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/commons.css">
</head>
<body>
{#    所有展示的内容居中显示#}
    <div style="text-align: center">
{#        标签内容用红色字体显示#}
        <p style="color: red;">this is list</p>
{#        循环遍历列表li#}
        {% for i in li %}
            <h4>{{ i }}</h4>
        {% endfor %}
        <p style="color: red;">this is if else</p>
{#        if else 循环#}
        {% if x == 1 %}
            <h4>1234</h4>
        {% else %}
            <h4>5678</h4>
        {% endif %}
{#        输出页面被刷新的时间#}
        <h1>Now time {{ now }}</h1>
    </div>
<script type="application/javascript" src="/static/js/jquery-2.2.1.min.js"></script>
<script type="application/javascript" src="/static/plugins/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
</body>
</html>

最后查看网页的运行效果

wKioL1bfrkLQ86tvAAEBtIYGxlY682.jpg


到这里,我们就可以结合python把我们想要的内容通过前端脚本语言呈现给用户了。

虽然模版语言提供了很多实用的方法,但是有时候我们为了实现功能需要自定义函数。要实现自定义模版函数功能我们需要进行如下的操作


1、在app01应用文件夹里创建一个名字叫做templatetags的模块(要注意是模块不是文件夹。文件夹里有添加一个_init_.py的空文件就变成模块了)

wKiom1bgGXSSz9T-AAAmzbvbfp0153.png


2、在templatetags目录下随便创建一个python文件。我这里就叫mytag.py,编辑该文件添加要自建的函数名称内容

mystag.py

#!/usr/bin/env python
# -*-coding:utf-8-*-
from django import template
from django.utils.safestring import mark_safe
from django.template.base import resolve_variable, Node, TemplateSyntaxError
register = template.Library()
创建函数sum_num返回两个参数相加之和
@register.simple_tag   #这个simple_tag是方法名不能随便乱改
def sum_num(num1,num2):
    z=num1+num2
    return z
创建函数添加一个input框
@register.simple_tag
def add_input(arg):
    result = "<input type='text' id='%s' />" %(arg,)
    一定要返回mark_safe(),如果直接返回result就会在网页字符串而不是input框
    return mark_safe(result)


3、检查子目录mydjango目录下面的settings.py文件是否有注册app01应用,如果不注册自定义的函数将无法被找到。

wKioL1bgLLrgRFHYAABsvmXt7_U845.png

4、修改app01目录下的views.py,将自定函数需要的参数以及参数的值传递给index.html

index.html

# /usr/bin/env python
# coding:utf-8
from django.shortcuts import render
import time
# Create your views here.
def index(request):
    # 将获取的当前时间格式化后赋值给now_time
    now_time = time.strftime('%Y-%m-%d %H:%M:%S')
    # 建立一个字典,将要传给html的变量作为key值,变量的内容作为value值
    index_dic = {
        'li': ['haha', 'hehe', 'heihei'],
        'x': 2,
        'now': now_time,
        #这是sum_num函数需要的参数
        'num1': 5,
        'num2': 6,
        #这是add_input函数需要的参数
        'my_str': 'test'
               }
    # 将字典导入render方法
    return render(request, 'index.html', index_dic)


5、修改templates目录下的index.html文件,要在文件最开头位置因为mytag.py文件,引入的语法格式为{% load mytab %}   引入之后就可以在下面的内容里调用自定义函数了。

index.html

{% load mytag %} 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.5-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/commons.css">
</head>
<body>
{#    所有展示的内容居中显示#}
    <div style="text-align: center">
{#        标签内容用红色字体显示#}
        <p style="color: red;">this is list</p>
{#        循环遍历列表li#}
        {% for i in li %}
            <h4>{{ i }}</h4>
        {% endfor %}
        <p style="color: red;">this is if else</p>
{#        if else 循环#}
        {% if x == 1 %}
            <h4>1234</h4>
        {% else %}
            <h4>5678</h4>
        {% endif %}
{#        输出页面被刷新的时间#}
        <h1>Now time {{ now }}</h1>
        <p>自定求和函数</p>
        {% sum_num num1 num2 %}
        <p>自定义input对话框</p>
        {% add_input my_str %}
    </div>
<script type="application/javascript" src="/static/js/jquery-2.2.1.min.js"></script>
<script type="application/javascript" src="/static/plugins/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
</body>
</html>

wKiom1bgLsnymbyQAABEqXHrJ8k703.png


最后打开浏览器验证自定义函数的运行效果

wKioL1bgL_Gy3c7YAAAsmPTEO9A539.png


到这里位置,我们就实现了在html文件中使用自定义函数的功能。