Part V: Django template layer

Template Syntax Notation

{} {} Related variables

Template template layer of traditional values

python all the basic data types passed to the html file support

int、float、str、list、tuple、dict、set、bool

In addition you can also pass functions, classes and objects, functions and objects which will automatically add the last incoming call parentheses execution.

Template syntax does not support parameter passing, so there is a reference function and call these classes do not support mass participation

To the rear end htmlin two ways to transfer data files:
1, by name

return render(request, 'index.html', {'n':n, 'f':f})

2、locals()

It sets the current namespace for all variable names passed to all html page

return render(request, 'index.html', locals())

The value

django template syntax value, only one mode of operation: a period character

  • .索引

  • .键

<p>{{ l.2 }}</p>
<p>{{ d.username }}</p>
<p>{{ d.password }}</p>
<p>{{ d.hobby.1.username.1 }}</p>

The filter template syntax

|length
|add
|default
|truncatechars
|truncatewords
|filesizeformat
|slice
|date
|safe
 
<p>过滤器  |左边的会当做过滤器的第一个参数 过滤器名右边的会当做过滤器的第二个参数</p>
<p>求数据长度:{{ s|length }}</p>
<p>加法运算:{{ n|add:10 }}、{{ s|add:13132 }}、{{ s|add:'DSB' }}</p>
<p>默认值(判断值是否为空):{{ b|default:'这个b布尔值是True' }}、{{ ff|default:'这个ff布 尔值是Flase' }}</p>
<p>截取字符(截取5个字符 三个点也算):{{ s|truncatechars:8 }}</p>
<p>截取单词(截取8个单词 三个点不算):{{ ss|truncatewords:8 }}、{{ sss|truncatewords:4 }}</p>
<p>文件大小:{{ file_size|filesizeformat }}</p>
<p>切片操作:{{ s|slice:'0:2' }}、{{ s|slice:"0:8:2" }}</p>
<p>日期格式化:{{ ddd|date:'Y年/m月/d日' }}</p>
<p>转义:{{ res|safe }}、{{ res1 }}、后端直接标识安全:{{ res2 }}</p>

Front and rear end unescaping

  • front end

    • |safe
  • rear end

    • from django.utils.safestring import mark_safe
      ```

    mark_safe('

    Safety

    ')
    ```

Summary: The front-end code do not have to write the front page, can be passed to write the front page in the back end, so that you can use to be more and more back-end logic syntax.

%}% {Logically related

The label template syntax

for loop:

{% for foo in l %}  <!--l = [1,2,3,4,5,6]-->
    {% if forloop.first %}
        <p>这是我的第一次</p>
    {% elif forloop.last %}
        <p>这是最后一次了啊~</p>
    {% else %}
        <p>{{ foo }}</p>
    {% endif %}
    {% empty %}  # 当for循环没有执行的情况下执行下面
    <p>for循环的对象内部没有值</p>
{% endfor %}

Custom filters, label, inclusion_tag

Define custom filters, labels and inclusion_tag requires the following preparatory work

1, the application name to create a new folder name to be called templatetags

2, a new arbitrary file name py folder in the file (eg: mytag)

3, in the document, you must write code for the following two

from django.template import Library
 
register = Library()

Custom filter

mytag.py:

@register.filter(name='my_sum')
def index(a, b):
    return a + b

html page:

<p>自定义过滤器的使用</p>
{% load mytag %}
<p>{{ 10|my_sum:90 }}</p>  # 10传入到a,90传入b
 
# 过滤器最多可以传入2个参数,如果想传入多个参数,可以将第二个参数传入列表

Use custom labels

mytag.py:

@register.simple_tag(name='my_baby')
def xxx(a, b, c, d):
    return '%s?%s?%s?%s?' % (a, b, c, d)

html page:

<p>自定义标签的使用</p>
{% load mytag %}
<p>{% my_baby 1 2 3 'hello world' %}</p>

Custom filters and custom labels distinction

<p>自定义的过滤器可以在逻辑语句中而自定义的标签不可以</p>
{% if 10|my_sum:100 %}
    <p>条件成立</p>
{% endif %}
 
{% if my_baby 1 2 3 4 %}
    <p>条件成立</p>
{% endif %}

Custom inclusion_tag

my_tag.py:

# 自定义inclusion_tag @register.inclusion_tag('demo.html',name='myin')
def index1(n):
    l = []
    for i in range(n):
        l.append(i)
    # 将列表传递给demo.html
    # return locals()
    return {'l':l}
 

html page:

<p>自定义inclusion_tag的使用</p>
{% load mytag %}
{% myin 5 %}
# 总结 页面上使用他们 统一先导入
    {% load mytag %}

Inherited template

When a page is common to most of the region, and that this page can be used as a template page

When other pages inherit this page and how to modify the corresponding area?

先在模板页面上通过block实现划定区域
    {% block content %}
        模板页面内容
    {% endblock %}
 
子页面中先导入整个模板
    {% extends '模板页面.html'%}
    修改特定的区域  通过实现划定好的区域名称
    {% block content %}
        子页面内容
    {% endblock %}
 
通常情况下 模板页面页面应该起码有三块区域
    {% block css %}
        模板页面内容
    {% endblock %}
 
    {% block content %}
        模板页面内容
    {% endblock %}
 
    {% block js %}
        模板页面内容
    {% endblock %}
# 模板的block块越多 可扩展性越高
 
# 还支持子页面调用父页面对应区域的内容 并且可以无限次调用
    {{ block.super }}
 

Importing templates

The html page as a module, where the need to guide where the html page is usually not complete, but a local style.

html page:

{% include 'left.html' %}

Plug-in design

The profile of django settings source implementation of project-based plug-in design

Directory structure is as follows:

conf file settings are exposed to the conf directory under the user's files under the lib directory

global_settings document is an internal profile

# conf/settings.py
 
NAME = '我是暴露给用户的配置文件'
# lib/conf/global_settings.py
 
NAME = '我是项目默认的配置文件'
# start.py
import os
import sys
 
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
 
if __name__ == '__main__':
    # 项目启动,就应向全局大字典中设置键值对
    os.environ['xxx'] = 'conf.settings'
    # lib/conf下没有settings文件,会去conf下的管理模块的__init__中查找
    from lib.conf import settings
    print(settings.NAME)
# lib/conf/__init__.py
 
import importlib
import os
from lib.confimport global_settings
 
class Settings(object):
    def __init__(self):
        # 先循环遍历项目默认的配置文件
        for name in dir(global_settings):
            # 判断变量名是否为大写
            if name.isupper():
                 # 键值对设置给对象
                 setattr(self, name, getattr(global_settings, name))
 
       # 先获取暴露给用户的配置文件的字符串路径
        # 获取start文件中的定义的全局大字典的xxx的values
        module_path = os.environ.get('xxx')
        # 通过importlib模块,导入暴露给用户的settings文件(conf下的)
        md = importlib.import_module(module_path)
        for name in dir(md):
            if name.isupper():
                setattr(self, name, getattr(md, name))
 
 
# 模块的单例模式,节省内存
settings = Settings()

If the effect is achieved in the conf configuration settings already exists, it will override the default configuration, if not, use the default configuration

Guess you like

Origin www.cnblogs.com/cnhyk/p/12173528.html