Custom filters static template file aliases inherited component reverse lookup

Content Today

  1. Template inheritance
  2. Package
  3. Custom filter
  4. inclusion_tag
  5. Static configuration file
  6. Alias ​​and reverse analysis
  7. url namespace

Template inheritance

Why template inheritance?

Found writing html page there are many pages have a similar style to create the wheel need not be repeated

Web framework needs a very convenient method for dynamically generating HTML pages. The most common approach is to use a template.

Part of the required template contains static HTML pages, as well as some special template syntax for the dynamic content into static parts.

Design templates implements business logic separated from the template view the contents of the display, a view can use any of a template, a template can be used for a plurality of views.

Template inheritance how to achieve?

1. 创建一个base.html页面(作为母版,其他页面来继承它使用 名字随便取)
2. 在母版中定义block块(可以定义多个,整个页面任意位置)
    {% block content %}  <!-- 预留的钩子,共其他需要继承它的html,自定义自己的内容content -->
    {% endblock %}
3 其他页面继承写法
    {% extends 'base.html' %}  必须放在页面开头
4 页面中写和母版中名字相同的block块,从而来显示自定义的内容
    {% block content %}  <!-- 预留的钩子,共其他需要继承它的html,自定义自己的内容 -->
        {{ block.super }}  #这是显示继承的母版中的content这个快中的内容
        这是xx1
    {% endblock %}
以下是具体运行代码

The first step to create a master template

Create a folder in the templatesmuban.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板</title>
    <style>
        {% block css %}
        #mub{
            width: 100%;
            height: 50px;
            background-color: cornflowerblue;
        }
        {% endblock %}{#预留的钩子,共其他需要继承它的html,自定义自己的内容#}
    </style>
</head>
<body>
<div id="mub">我是模板</div>

{% block content %}  <!-- 预留的钩子,共其他需要继承它的html,自定义自己的内容 -->
    <h1>我是模板h1</h1>
{% endblock %}
{% block cs2 %}  <!-- 预留的钩子,共其他需要继承它的html,自定义自己的内容 -->
    <h1>我是测试2</h1>
{% endblock %}
</body>
</html>

Step 2 other pages inherit wording

Home.html in templates to create a folder inherited from muban.html

{% extends 'muban.html' %}

{% block css %}
    #mub{
        width: 100%;
        height: 50px;
        background-color: red;
    }
    #s6{
        width: 50%;
        height: 50px;
        background-color: red;
        float: right;
    }
    {% endblock %}




{% block content %}  <!-- 预留的钩子,共其他需要继承它的html,自定义自己的内容 -->
<h1>我改变了模板的内容</h1>
<div id="s6">我来测试</div>
{% endblock %}


{% block cs2 %}  <!-- 预留的钩子,共其他需要继承它的html,自定义自己的内容 -->
    {{ block.super }}
    我在测试2下面
{% endblock %}

Package

Component is similar to the python modules when importing such as common when using the navigation bar, footer, general information and other components that we kept in a separate file, component encapsulates function templates can be modified

1 创建html页面,里面写上自己封装的组件内容,xx.html
2 新的html页面使用这个组件
    {% include 'xx.html' %}
以下是代码

Creating a component

Creating a component title.html in the templates folder

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .nav{
            background-color: pink;
            height: 40px;

        }

    </style>
</head>
<body>

<div class="nav">
    <span>个人中心</span>
    <span>首页</span>
    <span>注册</span>
    <span>登录</span>

</div>


</body>

</html>

Reference component

Home.html create a folder in the templates referenced components title.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
{% include 'title.html' %}

<h1>这是新项目首页</h1>

</body>
</html>

Custom filter

Why do we need custom tags and filters?

Because in reality programming may be built-in label filter does not meet all our needs we need to create their own

Create custom labels and filters Process

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

2 在xx.py文件中引用django提供的template类,写法
    from django import template
    register = template.Library() #register变量名称不能改
    
    # 自定义标签 没有参数个数限制
    from django import template
    register = template.Library() #register变量名称不能改

    @register.filter   #参数至多两个  也就是管道后最多只有一个
    def guolv(v1,v2):
        """
        :param v1: 变量的值 管道前面的
        :param v2: 传的参数 管道后面的,如果不需要传参,就不要添加这个参数
        :return: 
        """
        return v1+v2

        使用:
        {% load xx %} xx是py文件 先在HTML页面引入
        {{ name|guolv:'oo' }} 使用过滤器 guolv是自己定义的过滤器函数名
    
下面是执行的代码

4.7.2.1 Create a folder in the application folder and create a templatetags xx inside. File

from django import template
register = template.Library() #register变量名称不能改

@register.filter   #参数至多两个
def guolv(v1,v2):
    """
    :param v1: 变量的值 管道前面的
    :param v2: 传的参数 管道后面的,如果不需要传参,就不要添加这个参数
    :return: 
    """
    return v1+v2

4.7.2.2 view views code

from django.shortcuts import render,HttpResponse
name='测试+'
def home(request):
    return render(request,'home.html',{'name':name})

4.7.2.3 To create a custom filter references html page

{% load xx %}{#xx是templatetags文件夹下的xx.py文件#}
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
{{ name|guolv:'要传给n2的参数' }}

</body>
</html>

inclusion_tag

Multi html code segment for returning

Principle run first nue.html call xx.py function in res

res function returns the page ( 'result.html') to a value corresponding to the template @ register.inclusion_tag rendered to the original form of a unit nue.htm

nue.htm

{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% res a %}#a是参数

</body>

</html>

result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<ul>
    {% for i in li %}

        <li>{{ i }}</li>
    {% endfor %}
</ul>
</body>

</html>

xx.py

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

Static related files

Static configuration file

js, css, img and so is called a static file, then the configuration on django static files, we need to write the configuration file settings in which to write the contents on this:

Directory: Alias ​​is a safety mechanism on the browser via the commissioning stage you can see is the alias name, so that others can not know the name of your static folder, or else someone else will be able to attack through this folder path.

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

    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static_file'),
    ]
    
    
3 引入<link rel="stylesheet" href="/abc/css/index.css">

The first project to create a directory folder, for example named static_file, all the static files into this folder

1569493728264

2 find the configuration file settings make the following configuration

STATIC_URL = '/abc/'  #静态文件路径别名 可以随便改
   #注意第2个参数一定对应创建的文件夹名 别名可以随便改
   STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static_file'),
   ]

html page content introduced in the third profile

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/abc/css/index.css">
    <link rel="stylesheet" href="/abc/plugins/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>

<input type="text" class="form-control">
<h1>红浪漫spa会所</h1>
<img src="/abc/img/timg.jpg" alt="">
<a href="{% url 'home' %}">首页</a>

技师:
<ul>
    <li>小白</li>
    <li>小黑</li>
</ul>

</body>
</html>

Alias ​​and reverse analysis

We give an alias after starting url url-no matter how change can be achieved would not have written the original URL dead

rurl文件写法
    url(r'^index2/', views.index,name='cs'),
反向解析
    后端views:
         from django.urls import reverse 可以实现反向解析
         reverse('别名')  例如:reverse('cs') 反向解析为别名对应的地址 /index2/
         带参数的反向解析: reverse( index' ,args=(10,))--- /index2/10/
    html: {% url '别名' %} -- 例如:{% url 'cs' %} -- /index2/
下面是代码

rurl file written

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^cs/', views.home,name='cs'),
    url(r'^cs1/', views.cs1,name='cs1'),
]

Backend views.py

用于重定向 redirect
我们利用别名 以后不管 别名cs1 对应的网址这么变  我们通过反解析 ,都可以找到他,写活了他 
from django.shortcuts import render,HttpResponse,redirect
from django.urls import reverse

def home(request):
    return redirect(reverse('cs1'))
def cs1(request):
    return HttpResponse('测试')

url namespace

In route distribution may be in order to avoid confusion

from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^app01/', include('app01.urls',namespace='app01')),#app01/home/
    url(r'^app02/', include('app02.urls',namespace='app02')),
    
]


使用:
    后端:reverse('命名空间名称:别名') -- reverse('app01:home') 
    hmtl:{% url '命名空间名称:别名' %}  -- {% url 'app01:home' %}

Guess you like

Origin www.cnblogs.com/saoqiang/p/11628217.html