Template related operations

1. MVC framework and MTV framework

1. MVC framework

MVC:
    M -- models 数据库相关
    V -- views  视图相关(逻辑)
    C -- controller url控制器(url分发器,路由分发)

2. MTV framework

django -- MTV
    M -- models 数据库相关
    T -- templates HTML相关 html就是模板
    V -- views  视图(逻辑业务相关)
    
    + controller url控制器(url分发器,路由分发)

2. Grammar

Template rendering of official documents

  About templates to render you only need to remember two special symbols (syntax):

  {{ }}with{% %}

  Variable associated with {{}}, {logic associated with %%}.

3. Variables

1. omnipotent point call

{{ variable name}}

Variable names consist of alphanumeric and underscores.

Dot (.) Has a special meaning in the template language, corresponding to the acquired attribute of the object.

for example

views.py

from django.shortcuts import render
import datetime

def index(request):

    name = "水手"
    num = 100
    lst = [1, 2, "aa", "bb"]
    dic = {"xx": "oo", "xxx": "ooo"}
    date = datetime.date(1993, 5, 2)  # 日期对象

    class Person():
        n = "黑哥"

        def p(self):
            return "床前明月光"

    obj = Person()
    return render(request, "index.html", {"name": name, "num": num, "lst": lst, "dic": dic,"date":date, "obj": obj})
    # print(locals()) 获得全局字典,传的数据多,效率低
    # return render(request, "index.html", locals())

index.html Code

    <h1>24期官网</h1>
    <h2>{{ name }}</h2>    # 获得后端name的值渲染到页面
    <h2>{{ num }}</h2>     # 获得后端num的值渲染到页面
    <h2>{{ lst }}</h2>     # 获得后端lst的值渲染到页面
    <h2>{{ dic }}</h2>     # 获得后端dic的值渲染到页面
    <h2>{{ obj }}</h2>     # 获得后端obj的对象渲染到页面
    <h2>{{ lst.1 }}</h2>   # {#点索引获取对应的值#}
    <h2>{{ dic.xx }}</h2>   # {#点键获取字典的值#}
    <h2>{{ obj.n }}</h2>    # {#点属性获取值#}
    <h2>{{ obj.p }}</h2>    # {#点方法获取返回值,前端调用不加括号#}
    <h2>{{ dic.keys }}</h2> {#先查找字典中的键,有此键就不调用方法了#}
    <h2>{{ dic.items }}</h2>  # {#点方法获取字典的键值对#}
                            # {# dic.values获取值,dic.keys获取键 #}

2. order inquiry

  Dictionary lookup (Dictionary lookup)
  property or method query (Attribute or method lookup)
  digital index query (Numeric index lookup)

for example

dic = {"xx": "oo", "xxx": "ooo","keys":"我在执行我"}
<h2>{{ dic.items }}</h2> # 前端执行时先在字典中查询此键,有键就不执行字典的方法了
# 结果是: 我在执行我 而不是: dict_keys(['xx', 'xxx']) 键的列表

3. Notes

  1. Call the method does not support pass parameters .
  2. If variables does not exist, the system will insert the value string_if_invalid template option, which is the default setting is '' (the empty string)

4. Filter filter

1. Grammar

{{ value|filter_name }}

{{Value | filter_name: Parameter}}

2. Specific Examples

1. default default

NOTE: ':' There is no space left no space is no space, nothing needs quotation marks

<h2>{{ age|default:"Nothing" }}</h2>     # 变量不存在,显示为空字符串,设置默认值
返回同样是nothing的还有有这个变量,但是值是False,空字典等值为空的

Note: TEMPLATES The OPTIONS can add an option: string_if_invalid: 'find', can replace the default role

见上述做修改部分替代default的作用
在settings文件中TEMPLATES的'OPTIONS'字典中再添加一个键值对 "string_if_invalid":"不存在或为空" 为空时或不存在时执行

2. filesizeformat

Value formatted as a "human readable" format size (e.g. '13 KB ',' 4.1 MB ',' 102 bytes', etc.)

{{ value|filesizeformat }}   #如果 value 是 123456789,输出将会是 117.7 MB

3. add add

<h2>{{ num|add:22 }}</h2>    #  html语法加不加引号效果相同
<h2>{{ num|add:"22" }}</h2>  #  html语法加不加引号效果相同 num=100  结果:122
    <h2>{{ lst|add:lst }}</h2> #
    <h2>{{ name|add:"bsb" }}</h2> # 也可以用于字符串和列表等的相加

4. length length

<h2>{{ name|length }}</h2>  # 字符长度
<h2>{{ lst|length }}</h2>   # 列表长度
<h2>{{ dic|length }}</h2>   # 字典长度
<h2>{{ name|add:"bsb"|length }}</h2>  # 多重操作

5. slice sliced

<h2>{{ name|add:"abcdefg"|slice:"2:-1:2" }}</h2>  # ace  支持切片和步长

6. first takes a first value

<h2>{{ name|first }}</h2>  # 获取第一个值
<h2>{{ value|last }}</h2>  # 获取最后一个值      

7. join splicing

<h2>{{ name|join:"//" }}</h2>  # 结果 水//手 相当于字符串拼接
<h2>{{ dic|join:"//" }}</h2>   # 键拼接  xx//xxx
<h2>{{ lst|join:"//" }}</h2>   # 迭代拼接 1//2//aa//bb

8. truncatechars

If the string of characters is more than a specified number of characters, it will be truncated. Truncated strings will be translated sequence ellipsis ( "...") at the end

<h2>{{ "abcdefghigk"|truncatechars:3 }}</h2>  #  ...    保留几个字符,小于三也是三个点
<h2>{{ "abcdefghigk"|truncatechars:6 }}</h2>  # abc...  保留6个,有三个点

9. date Date Format

date = datetime.date(1993, 5, 2)  # 日期对象
now = datetime.datetime.now()     # 现在时间

<h2>{{ date|date:"Y-m-d"}}</h2>   #
<h2>{{ now|date:"Y-m-d H:i:s"}}</h2> #  设置显示格式

Extension with no filter, modify the settings provided

# USE_L10N = True
USE_L10N = False

DATETIME_FORMAT = "Y-m-d H:i:s"
DATE_FORMAT = "Y-m-d"
TIME_FORMAT = "H:i:s"

<h2>{{ date }}</h2>   #
<h2>{{ now }}</h2> #  设置显示格式

10. safe

bd = '<a href="http://www.baidu.com">百度</a>' # 后端

前端:
    <h2>{{ bd }}</h2>     # 显示字符串 <a href="http://www.baidu.com">百度</a>
    <h2>{{ bd|safe }}</h2> # 设置safe,显示为a标签 百度

11. truncatewords

msg = "我 是 i love you my baby"

<h3>{{ msg|truncatewords:2 }}</h3> # {#  以空格区分截断,不是字符字节  #} 我 是 ...
<h3>{{ msg|truncatechars:2 }}</h3> # 注意二者的区分  ...

5. Custom filter

1. Custom filter

1. Create a package called templatetags (templatetags name can not be changed) in the app

2. Create py file in the package (the file name can be customized my_tags.py)

3. Write code my_tags.py in:

from django import template
register = template.Library()  # register名字不能错,固定

4. Write a function of decorator + Add

@register.filter
def xx(v1,v2):
    ret = v1+v2
    return ret.upper()

5. Use

in index.html

{% load my_tags %}   # 加载py文件
{{ "alex"|xx:"dsb" }}  # alex和dsb 分别对应两个参数,渲染返回值
                    # 参数至多两个,至少一个   name = "alex"可以通过index函数传递

6. Other wording

from django import template

register = template.Library()

@register.filter
def xx(v1,v2="dsb"):
    ret = v1 + v2
    return ret.upper()

{% load my_tags %}
{{ "alex"|xx }}     # 后端添加默认参数  ALEXDSB

Only one parameter

from django import template

register = template.Library()

@register.filter
def xx(v1):
    ret = v1
    return ret.upper()

{% load my_tags %}
{{ "alex"|xx }}     # 后端添加默认参数  ALEX

An alias to the function

from django import template

register = template.Library()

@register.filter(name="xxsb")
def xx(v1,v2):
    ret = v1 + v2
    return ret.upper()

{% load my_tags %}
{{ "alex"|xxsb:"dsb" }}   # 注意用别名  ALEXDSB

1. custom tags and filters

1 在应用app01下创建一个叫做templatetags的包(名称不能改),在里面创建一个py文件,例如xxoo.py
2 在xxoo.py文件中引用django提供的template类,写法
    from django import template
    #register名称不可变,library大写
    register = template.Library()
    
    #定义过滤器
    @register.filter   # 参数至多两个
    def xx(v1,v2):
        return v1+v2
    使用:
        {% load xxoo %}   # 加载上文件名xxoo,相当于引入xxoo.py文件
        {{ name|xx:'oo' }}  # xx是函数名 传两个参数
    
    # 自定义标签 没有参数个数限制
    @register.simple_tag
    def huxtag(n1,n2):  #冯强xx  '牛欢喜'
        '''
        :param n1:  变量的值 管道前面的
        :param n2:  传的参数 管道后面的,如果不需要传参,就不要添加这个参数
        :return:
        '''
        return n1+n2

    # inclusion_tag 返回html片段的标签
    @register.inclusion_tag('result.html')
    def res(n1): #n1 : ['aa','bb','cc']

        return {'li':n1 }
    使用:
        {% res a %}
    

1. custom tags and filters premise

1 在应用下创建一个叫做templatetags的文件夹(名称不能改),在里面创建一个py文件,例如xxxx.py

2 在xx.py文件中引用django提供的template类,写法
    from django import template
    #register名称不可变,library大写
    register = template.Library()

2. Define the filter

1. 页面请求 127.0.0.1/new/
2. 找到 url(r'^test/', views.test) 执行 new函数
3. new有第三个参数,{"name":"Alex"}传到new.html文件中
4. {{ name|addoo:"dsb"}}加载xx.py文件,调用xx中的addoo函数
5. 执行xx中的res函数 return n1+n2,参数一一对应
6.替换new.html中内容,响应浏览器,显示结果

3. Custom Labels

1. 页面请求 127.0.0.1/new/
2. 找到 url(r'^new/', views.new) 执行 new函数
3. new有第三个参数,{"name":"Alex"}传到new.html文件中
4. {% load xx %}加载xx.py文件,调用{% res name "dsb" %}函数
5. 执行xx中的res函数 return n1+n2,参数一一对应
6.替换new.html中内容,响应浏览器,显示结果

4. inclusion_tag return label fragment html

1. 页面请求 127.0.0.1/new/
2. 找到 url(r'^new/', views.new) 执行 new函数
3. new有第三个参数,{"a":a}传到new.html文件中
4. {% load xx %}加载xx.py文件,调用{% res a "s2" %}函数
5. 执行xx中的res函数
6. 将return值返回给@register.inclusion_tag("result.html")的result.html
7. 修饰后依次跳回new.html文件,响应浏览器,显示结果

4. Static configuration file

1 项目目录下创建一个文件夹,例如名为jingtaiwenjianjia,将所有静态文件放到这个文件夹中
2 settings配置文件中进行下面的配置
    # 静态文件相关配置
    STATIC_URL = '/abc/'  #静态文件路径别名

    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'jingtaiwenjianjia'),
    ]

3 引入<link rel="stylesheet" href="/abc/css/index.css">
4.写引入文件的小窍门
    用别名时,写路径过程中没有提示,可以先写真正的名字,有提示,当所有路径写全后,再改为别名

Guess you like

Origin www.cnblogs.com/lvweihe/p/11754647.html