Django template inheritance [five] / components / custom filters (label)

First, label tags

for labels

Through each element: write for, and then automatically generate the tab key structure for the cycle, the cycle is very basic, so simple use, there is no break and the like, complex functions, you have to pass js

def get(self,request):
      lit = ["","",""]
      return render(request,"login.html",{"lit":lit})
wsgi
{% for foo in lit %}
    {{ forloop.counter}} {{  foo  }}
{% endfor %}
html code

Tag looks like this:  {% tag %}. Tag is more complex than a variable: some additional information creating in the output text, a number or to control flow through the logic loop, some variables will be used to load subsequent to the template. Some tags require the start and end tags (e.g., {% tag %} ...tag content ... {% endtag%}).

NOTE: cycle number can be displayed {{forloop}}, must be used inside the loop

Copy the code
forloop.counter current index value of the cycle (starting at 1), magic forloop circulator to function through the use of point 
forloop.counter0 current cycle index value (zero) 
forloop.revcounter inverted index value of the current cycle (starting at 1 ) 
forloop.revcounter0 reverse current cycle index value (zero) 
forloop.first not the current cycle is the first cycle (Boolean) 
forloop.last current cycle is not the last cycle (Boolean) 
forloop.parentloop while inside the loop layer of the present for the outer loop, then the outer loop count is displayed by several properties like the above
Copy the code

 You may be utilized {%  for  obj  in  List  the reversed  %} reverse completing the cycle.

empty

for  label with an optional {%  empty  %}  clause, in order to give set is empty or not is found, the operation may be

def get(self,request):
      lit = []
      return render(request,"login.html",{"lit":lit})
View function
{% for foo in lit reversed %}
    {{ forloop.counter}} {{  foo  }}
{% empty %}
    sorry
{% endfor %}
html code

if the label

% {  IF  %} be a variable evaluation, if its value is "True" (exists, it is not empty, and not false boolean value type), the block will output the corresponding content.

Copy the code
IF NUM% {> 100 or NUM <} 0% 
    <P> Invalid </ p> <-! Condition is not satisfied, the label does not generate -> 
{% elif NUM> NUM 80 and <100%} 
    <P > Elite </ P> 
{%}% the else <-! if the tag is inside the structure of the -> 
    <P> Minato live it </ P> 
{%} endif%
Copy the code

Of course, there may be only if and else

{% If user_list | length> 5 %} <- used in conjunction with a filter ->! 
  Seven luxury the SUV 
{%}% the else 
    rickshas 
{% endif%}

if statement supports and, or, ==,>, <,! =, <=,> =, in, not in, is, is not to judge, pay attention to the conditions on both sides spaces.

Precautions

    1. Django template language does not support continuous judgment that does not support the following wording:

{% if a > b > c %}
...
{% endif %}

    2. Django template language's priority attribute is greater than the method (understand)

def xx(request):
    d = {"a": 1, "b": 2, "c": 3, "items": "100"}
    return render(request, "xx.html", {"data": d})

      As above, when we use the render method to render a page, pass a dictionary d key items and there is a default d.items () method, this time in the template language:

{{ data.items }}

      Default items key will take the d.

二、csrf_token

We post way when the form is submitted, will complain, remember we are inside the middleware configuration settings inside the csrf a defense mechanism to write-off the ah, itself should not be written off, but should learn how to use it, and do not to make their operation is forbiden, be able to get through this thing.

    This tag is used CSRF protection,

    In the pages of the form form inside (note in the form form inside) write anywhere on {% csrf_token%}, this thing when rendering templates replaced with <input type = "hidden" name = "csrfmiddlewaretoken" value = "8J4z1wiUEXt0gJSN59dLMnktrXFW0hv7m4d40Mtl37D7vJZfrxLir9L3jSTDjtG8" > hidden, the value of this tag is a random string, when submitted, this thing has also been submitted, the first thing is our back-end rendering time to add the page, then when you pass I gave you form when the form is submitted the data, you take the content I've known you, not with, I forbid you, because we django also kept the background of this thing, and a value of the same value you can do is not to verify the corresponding I'll give you a token, store this stuff values ​​behind us to learn, you know first click on the line, just like one of us back to the users of a pass, if you are a user does not follow me give you the normal page to post submit the form data, or that you did not ask me to go to this landing page, but directly mold Request to submit the data, then I can tell you that the request is illegal, anti-reptile or a malicious attack on my website, after the middleware we elaborate in this thing, but now you have to understand how it happened, understand Why django will add this set of defense.

 

<form Action = " / Login / " Method = " POST " > 
    { % csrf_token%}   # added anywhere in form in the form of 
    a user name: <input type = " text " name = " username " > 
    Password: <INPUT type = " password " name = " password " > 
    <Button> log </ Button> 
</ form>
Cross-site request forgery protection

CSRF protection in several applications:

1, the overall configuration (in settings)

This configuration represents the post request to all csrf added defense mechanism;

2, the two forms of the decorator

from django.views.decorators.csrf Import csrf_exempt
     # release csrf authentication, even if the global configuration of the authentication csrf 
    @csrf_exempt
     # function executing post request 
    DEF post (Self, Request): 
        User = request.POST.get ( " username " ) 
        pwd = request.POST.get ( " password " )
         IF User == " Chao "  and pwd == " 123 " :
             return the render (Request, " successfully.html " )
        the else :
             return HttpResponse ( " Username Password error " ) 

released csrf certification
Certified release csrf
from django.views.decorators.csrf import csrf_protect
    # 强制csrf认证,即便是全局没有配置csrf认证
    @csrf_protect
    # post请求执行的函数
    def post(self,request):
        user = request.POST.get("username")
        pwd=request.POST.get("password")
        if user=="chao" and pwd=="123":
            return render(request,"successfully.html")
        else:
            return HttpResponse("用户名密码错误")

强制csrf认证
强制csrf认证

三、模板继承

Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可以让您创建一个基本的“骨架”模版,它包含您站点中的全部元素,并且可以定义能够被子模版覆盖的 blocks 

创建模板:

Copy the code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        {% block style %}
        .c1{
            background-color: red;
            height: 200px;
            width: 200px;
        }
        {% endblock %}
    </style>
</head>
<body>

<div class="c1">
    {% block content %}
    <p>这是模板</p>
    {% endblock %}
</div>

</body>
</html>
Copy the code
1
2
3
4
5
{ %  block content  % }
     <p>这是模板< / p>
{ %  endblock  % }
 
凡是被大括号包裹的内容表示,该模板被继承后这个内容可以自定义

继承模板:

Copy the code
<!--继承模板,必须写在最上面-->
{% extends '模板.html' %}

{% block style %}
    .c1{
        background-color: yellow;
        height: 100px;
        width: 100px;
    }
{% endblock style %}

{% block content %}

    <!--保留模板内容-->
     {{ block.super }}

    <p>继承后重写样式</p>

{% endblock content %}
Copy the code

根据名字指定到哪里结束,使用block.super可以保留模板内容

  • 为了更好的可读性,你也可以给你的 {% endblock %} 标签一个 名字 。例如:

{% block content %}
...
{% endblock content %}  

   在大型模版中,这个方法帮你清楚的看到哪一个  {% block %} 标签被关闭了。

  • 不能在一个模版中定义多个相同名字的 block 标签。

四、组件

嵌入语法:

{% include 'navbar.html' %}

可以将常用的页面内容如导航条,页尾信息等组件保存在单独的文件中,然后在需要使用的地方,文件的任意位置按如下语法导入即可。

例如:有个如下的导航栏,nav.html

Copy the code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1{
            background-color: red;
            height: 40px;
        }
    </style>
</head>
<body>

<div class="c1">
    <div>
        <a href="">xx</a>
        <a href="">dd</a>
    </div>
</div>

</body>
</html>
Copy the code

嵌入导航栏的页面,test.html

Copy the code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% include 'nav.html' %}
<h1>xxxxxxxxxx</h1>
</body>
</html>
Copy the code

组件和插件的简单区别:

组件是提供某一完整功能的模块,如:编辑器组件,QQ空间提供的关注组件 等。

而插件更倾向封闭某一功能方法的函数。

这两者的区别在 Javascript 里区别很小,组件这个名词用得不多,一般统称插件。
View Code

五、自定义标签和过滤器

自定义过滤器:

@register.filter

一、app01应用文件夹中创建一个叫做templatetags的文件夹;

例如:

二、创建视图函数并传参数

def tags(request):
    num=100
    return render(request,"tags.html",{"num":num})
视图函数

三、在templatetags文件夹里创建一个py文件用于创建过滤器;

from django import template
# 生成模板注册器
register = template.Library()

@register.filter
def func(v1,v2):
    """
    过滤器参数
    :param v1: 变量值
    :param v2: 过滤器参数值
    :return:
    """
    return v1*v2

自定义过滤器
自定义过滤器

四、在前端页面导入过滤器并放变量等待接收参数

{% load mytag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ num|func:10 }}
</body>
</html>

导入过滤器
Import filter

Note: {% load mytag%} must be placed across the top of html

 

Conclusion: That num server receiving transfer parameters 100, and after our custom filters plus a second work, and finally the return value of the filter to a front end of the return value {{}}

The parameters of the filter can only have a maximum of two:

We want to pass multiple parameters are as follows:

Results page:

If you use template inheritance and custom filters, the order of introduction:

Custom Tags:

 Step 2 with a custom filter:

@register.simple_tag()

After the order is placed XSS attack so rendered in a template in the tag custom tag returned or text

The effect of the front page:

Use mark_safe () method allowed the normal display tags:

 

Results page:

 @ Register.inclusion_tag ( "filename .html")

Guess you like

Origin www.cnblogs.com/youxiu123/p/11600365.html