Django入门开发实战

Django---模版层

2018-12-10  本文已影响10人  乔治大叔

一 模版简介

你可能已经注意到我们在例子视图中返回文本的方式有点特别。 也就是说,HTML被直接硬编码在 Python代码之中。

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

尽管这种技术便于解释视图是如何工作的,但直接将HTML硬编码到你的视图里却并不是一个好主意。 让我们来看一下为什么:

基于这些原因,将页面的设计和Python的代码分离开会更干净简洁更容易维护。 我们可以使用 Django的 模板系统 (Template System)来实现这种模式,这就是本章要具体讨论的问题

** python的模板:HTML代码+模板语法**

def current_time(req):
    # ================================原始的视图函数
    # import datetime
    # now=datetime.datetime.now()
    # html="<html><body>现在时刻:<h1>%s.</h1></body></html>" %now


    # ================================django模板修改的视图函数
    # from django.template import Template,Context
    # now=datetime.datetime.now()
    # t=Template('<html><body>现在时刻是:<h1>{{current_date}}</h1></body></html>')
    # #t=get_template('current_datetime.html')
    # c=Context({'current_date':str(now)})
    # html=t.render(c)
    #
    # return HttpResponse(html)


    #另一种写法(推荐)
    import datetime
    now=datetime.datetime.now()
    return render(req, 'current_datetime.html', {'current_date':str(now)[:19]})

模版语法重点:

变量:{{ 变量名 }}

1 深度查询 用句点符

2 过滤器

标签:{{% % }}

二 模版语法之变量

在 Django 模板中遍历复杂数据结构的关键是句点字符, 语法:{{变量名}}

views.py

def template_test(request):
    name = 'lqz'
    li = ['lqz', 1, '18']
    dic = {'name': 'lqz', 'age': 18}
    ll2 = [
        {'name': 'lqz', 'age': 18},
        {'name': 'lqz2', 'age': 19},
        {'name': 'egon', 'age': 20},
        {'name': 'kevin', 'age': 23}
    ]
    ll3=[]
    class Person:
        def __init__(self, name):
            self.name = name

        def test(self):
            print('test函数')
            return 11

        @classmethod
        def test_classmethod(cls):
            print('类方法')
            return '类方法'

        @staticmethod
        def static_method():
            print('静态方法')
            return '静态方法'

    lqz = Person('lqz')
    egon = Person('egon')
    person_list = [lqz, egon]
    bo = True
    te = test()
    import datetime
    now=datetime.datetime.now()
    link1='<a href="https://www.baidu.com">点我<a>'
    from django.utils import safestring
    link=safestring.mark_safe(link1)
    # html特殊符号对照表(http://tool.chinaz.com/Tools/htmlchar.aspx)

    # 这样传到前台不会变成特殊字符,因为django给处理了
    dot='&spades;'


    # return render(request, 'template_index.html', {'name':name,'person_list':person_list})
    return render(request, 'template_index.html', locals())

html

<p>{{ name }}</p>
            <p>{{ li }}</p>
            <p>{{ dic }}</p>
            <p>{{ lqz }}</p>
            <p>{{ person_list }}</p>
            <p>{{ bo }}</p>
            <p>{{ te }}</p>

            <hr>
            <h3>深度查询句点符</h3>
            <p>{{ li.1 }}</p>
            <p>{{ dic.name }}</p>
            <p>{{ lqz.test }}</p>
            <p>{{ lqz.name }}</p>
            <p>{{ person_list.0 }}</p>
            <p>{{ person_list.1.name }}</p>

            <hr>
            <h3>过滤器</h3>
            {#注意:冒号后面不能加空格#}
            <p>{{ now | date:"Y-m-d H:i:s" }}</p>

            {#如果变量为空,设置默认值,空数据,None,变量不存在,都适用#}
            <p>{{ name |default:'数据为空' }}</p>
            {#计算长度,只有一个参数#}
            <p>{{ person_list |length }}</p>
            {#计算文件大小#}
            <p>{{ 1024 |filesizeformat }}</p>

            {#字符串切片,前闭后开,前面取到,后面取不到#}
            <p>{{ 'hello world lqz' |slice:"2:-1" }}</p>
            <p>{{ 'hello world lqz' |slice:"2:5" }}</p>

            {#截断字符,至少三个起步,因为会有三个省略号(传负数,1,2,3都是三个省略号)#}
            <p>{{ '刘清政 world lqz' |truncatechars:"4" }}</p>
            {#截断文字,以空格做区分,这个不算省略号#}
            <p>{{ '刘清政   是      大帅比 谢谢' |truncatewords:"1" }}</p>

            <p>{{ link1 }}</p>
            <p>{{ link1|safe }}</p>
            <p>{{ link }}</p>

            <p>&spades;</p>
            <p>{{ dot }}</p>

            {#add   可以加负数,传数字字符串都可以#}
            <p>{{ "10"|add:"-2" }}</p>
            <p>{{ li.1|add:"-2" }}</p>
            <p>{{ li.1|add:2 }}</p>
            <p>{{ li.1|add:"2" }}</p>
            <p>{{ li.1|add:"-2e" }}</p>

            {#upper#}
            <p>{{ name|upper }}</p>
            <p>{{ 'LQZ'|lower }}</p>
            <hr>
            <h3>模版语法之标签</h3>
            {#for 循环 循环列表,循环字典,循环列表对象#}
            <ui>
                {% for foo in dic %}
                    {{ foo }}
                {% endfor %}
                {#也可以混用html标签#}
                {% for foo in li %}
                    <ul>foo</ul>

                {% endfor %}
            </ui>
            {#表格#}
            <table border="1">

                {% for foo in ll2 %}
                    <tr>
                        <td>{{ foo.name }}</td>
                        <td>{{ foo.age }}</td>
                    </tr>
                {% endfor %}
            </table>
            <table border="1">
                {#'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 4, 'revcounter0': 3, 'first': True, 'last': False}#}
                {% for foo in ll2 %}
                    <tr>
                        <td>{{ forloop.counter }}</td>
                        <td>{{ foo.name }}</td>
                        <td>{{ foo.age }}</td>
                    </tr>
                {% endfor %}


            </table>



            {% for foo in ll5 %}
                <p>foo.name</p>
            {% empty %}
                <p>空的</p>
            {% endfor %}

            <hr>
            <h3>if判断</h3>
            {% if name %}
                <a href="">hi {{ name }}</a>
                <a href="">注销</a>
            {% else %}
                <a href="">请登录</a>
                <a href="">注册</a>
            {% endif %}
            {#还有elif#}
            <hr>
            <h3>with</h3>
            {% with ll2.0.name as n %}
                {{ n }}
            {% endwith %}
            {{ n }}


            {% load my_tag_filter %}

            {{ 3|multi_filter:3 }}

            {#传参必须用空格区分#}
            {% multi_tag 3 9 10 %}

            {#可以跟if连用#}
            {% if 3|multi_filter:3 > 9 %}
                <p>大于</p>
            {% else %}
                <p>小于</p>
            {% endif %}

注意:句点符也可以用来引用对象的方法(无参数方法):

<h4>字典:{{ dic.name.upper }}<``/``h4>

上一篇 下一篇

猜你喜欢

热点阅读