1. 程式人生 > 其它 >模板層

模板層

模板層

模板語法的傳值

{{}}: 變數相關
{%%}: 邏輯相關

<p>{{ n }}</p>
<p>{{ f }}</p>
<p>{{ s }}</p>
<p>{{ b }}</p>
<p>{{ l }}</p>
<p>{{ d }}</p>
<p>{{ t }}</p>
<p>{{ se }}</p>
<p>傳遞函式會自動加括號呼叫,並且返回給前端返回值,但是不能傳參:{{ func }}</p>

<p>傳類名的時候也會自動加括號呼叫例項化{{ Myclass }}</p>
<p>{{ obj }}</p>
<p>{{ obj.get_self }}</p>
<p>{{ obj.get_func }}</p>
<p>{{ obj.get_class }}</p>

"""
物件被展示到html頁面上 就類似列印了,也會觸發__str__方法

取值:
  句點符
  <p>{{ d.username }}</p>
<p>{{ l.0 }}</p>
<p>{{ d.hobby.3.info }}</p>

既可以點索引也可以點健,還可以混用
"""


def index(request):
    # 模板語法可以傳遞的後端資料型別
    n = 123
    f = 1.23
    s = 'qwe'
    b = True
    l = ['jason', 'egon']
    t = (111, 222, 333, 444)
    d = {'username': 'egon', 'age': 19}
    se = {'qwe', 'asd', 'zcx'}


    def func():
        return '返回了我的執行結果'

    class Myclass(object):
        def get_self(self):
            return 'self'

        @staticmethod
        def get_func():
            return 'func'

        @classmethod
        def get_class(cls):
            return 'cls'
    obj = Myclass()
    # return render(request, 'index.html', {}) # 可以寫一個字典一個一個傳
    return render(request, 'index.html', locals()) # 全部傳

過濾器

比較簡單的內建方法

轉義:
	前端 |safe
    後端: 
    	from django.utils.safestring import mark_safe
        res = mark_safe('<h1>qwe</h1>')
# 基本語法
{{資料 | 過濾器:引數}}

def index(request):
    # 模板語法可以傳遞的後端資料型別
    n = 123
    f = 1.23
    s = 'qwe'
    b = True
    b1 = False
    l = ['jason', 'egon', 123, 132, 23, 23]
    t = (111, 222, 333, 444)
    d = {'username': 'egon', 'age': 19, 'hobby': [111,222,333, {'info': 'NB'}]}
    se = {'qwe', 'asd', 'zcx'}
    file_size = 1233441 # KB, GB,
    import datetime
    current_time = datetime.datetime.now()
    info = '我是你爹我是你爹我是你爹我是你爹我是你爹'
    egl = 'my name is lyh my age is 14 my name is lyh my age is 14 '

    msg = '我 是 你 爹'

    hhh = '<h1>爸爸</h1>'


    def func():
        return '返回了我的執行結果'

    class Myclass(object):
        def get_self(self):
            return 'self'

        @staticmethod
        def get_func():
            return 'func'

        @classmethod
        def get_class(cls):
            return 'cls'
    obj = Myclass()
    # return render(request, 'index.html', {}) # 可以寫一個字典一個一個傳
    return render(request, 'index.html', locals()) # 全部傳


<h1>過濾器</h1>
<p>統計長度: {{ s|length }}</p>
<p>預設值: {{ b|default:'啥也不是' }}</p>
<p>預設值(第一個引數bool值是true,否則展示default後面的): {{ b1|default:'啥也不是' }}</p>
<p>檔案大小: {{ file_size|filesizeformat }}</p>
<p>日期格式化: {{ current_time|date:'Y-m-d H:s:m' }}</p>
<p>切片操作,支援步長: {{ l|slice:'0:4' }}</p>
<p>切取字元(包含三個點): {{ info|truncatechars:9 }}</p>
<p>切取單詞(不包含三個點 只會按照空格切): {{ egl|truncatewords:9 }}</p>
<p>移除特定的字元: {{ msg|cut:' ' }}</p>
<p>拼接: {{ l|join:'+' }}</p>
<p>拼接(加法): {{ n|add:10 }}</p>
<p>拼接(加法): {{ s|add:msg }}</p>
<p>取消轉義(告訴html, 前面那個標籤可以轉): {{ hhh|safe }}</p>

標籤

for 迴圈
{% for foo in l %}
    <p>{{ forloop }}</p>
    
    <p>{{ i }}</p>  # 所有的元素
{% endfor %}

{'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 6, 'revcounter0': 5, 'first': True, 'last': False}

if判斷

{% if b %}
    <p>baby</p>
{% else  %}
    <p>s</p>
{% else %}
    <p>123</p>
{% endif %}


{#{% for foo in l %}#}
{#    {% if forloop.first %}#}
{#        <p>第一次迴圈</p>#}
{#    {% elif forloop.last %}#}
{#        <p>最後一次迴圈</p>#}
{#    {% else %}#}
{#    <p>{{ foo }}</p>#}
{#    {% endif %}#}
{##}
{#{% endfor %}#}

{#{% for foo in d.keys %}#}
{#    <p>{{ foo }}</p>#}
{#{% endfor %}#}
{##}
{#{% for foo in d.values %}#}
{#    <p>{{ foo }}</p>#}
{#{% endfor %}#}
{##}
{#{% for foo in d.items %}#}
{#    <p>{{ foo }}</p>#}
{#{% endfor %}#}
    
{% with d.hobby.3.info as nb %}
    <p>起別名{{ nb }}</p>
{% endwith %}
<p>{{ d.hobby.3.info }}</p>

    
    

自定義過濾器,標籤,inclusion_tag

三步走:
	1.在應用下建立一個名字必須交templatetags的資料夾
    2.在該資料夾內建立任意名稱的py檔案 eg:mytag.py
    3.在該py檔案內必須書寫下面兩句話
    	--from django import template
        --register = template.Library()
        
        
    @register.filter(name='bbb')
    def my_sum(v1, v2):
        return v1 + v2
    
    {% load mytag %}
    <p>{{ n|bbb:666 }}</p>

    
    
    # 自定義標籤(引數可以有多個)
    @register.simple_tag(name='plus')
    def index(a, b, c, d):
        return '%s-%s-%-%s' % (a, b, c, d)
    

    {% load mytag %}
    <p>{% tplus 'jaosn' 12 3 3 %}</p>

自定義inclusing_tag

"""
內部原理:
	先定義一個方法
	在頁面上呼叫該方法,並且可以傳值
	該方法會生成一些資料然後傳給html頁面
	之後將渲染好的結果放到呼叫位置
"""

{% load mytag %}
{% left 10 %}

<ul>
    {% for foo in data %}
        <li>{{ foo }}</li>
    {% endfor %}

</ul>

#自定義inclusion_tag
@register.inclusion_tag('left_menu.html')
def left(n):
    data = ['第{}項'.format(i) for i in range(n)]
    return locals()  # 將data傳給left_menu.html
    # return {'data': data}  # 第二種傳值
    
"""
當html的某一個頁面需要傳引數才能動態的渲染出來,並且在多個頁面上都需要使用到該區域性,那麼就考慮將該區域性頁面做成這種格式
"""

模板的繼承

E:\pythonDemo\django專案\create_surface_relationship

先選好一個要繼承的頁面
{% extends 'home.html' %}


{% block content %}
    <h1>登入頁面</h1>
    <form action="">
        <p>username: <input type="text" name="username" class="form-control"></p>
        <p>password: <input type="password" name="password" class="form-control"></p>
        <input type="submit" class="btn btn-danger">
    </form>
{% endblock %}

繼承了頁面是一養的,在繼承的模板頁面劃定區域,子頁面就可以宣告劃定的區域
                        {% block content %}
                            <div class="jumbotron">
                                <h1>Hello, world!</h1>
                                <p>...</p>
                                <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
                            </div>
                        {% endblock %}
                        
一般情況下模板頁面上至少有三塊可以被修改的取餘
1.css
2.html
3.js

模板的匯入

將頁面的某一個區域性當成模組的形式
那個頁面需要使用匯入即可