django - template inheritance

csrf_token

When we submitted before the post request, are commented out in the setting.py file 'django.middleware.csrf.CsrfViewMiddleware' this line, this is the time of submission of the form data as form, Django prevent a malicious person to attack, for security considerations, Imagine, write your own django background, someone else write a page, action in the write address is the address of your server, if the person write attack code is your site, if you do not do school site test it received. It is likely to go wrong, it will reject django default swap post request, you do not want to comment out the line of code, values ​​need to add the following line of code in a single form on it

{% csrf_token %}

This time we went to see the web page code, you will find more than a page hidden input tag, so Django can distinguish our own or someone else to write the HTML file, the HTML file if there are no line will error

<input type="hidden" name="csrfmiddlewaretoken" value="Faz2aNAt5PaPVW93espQ12sT9DyZtqqIpsSC089vfcdgA072I4dTMbPzsStKxmUB">

 motherboard

When we write HTML, some pages are generally the same, such as blog park, only the second part is different from the rest is the same, this time we can put the common code is extracted, we will usually mother plate blocks define page specific CSS and JS block to facilitate the sub-page replacement.

public_main.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <title>Dashboard Template for Bootstrap</title>
    <!-- Bootstrap core CSS -->
    <link href="/static/bootstrap-3.3.7/css/bootstrap.css" rel="stylesheet">
    <link href= "/ static / dashboard.css" the rel = "this stylesheet" > 
</ head > 

< body > 


  < div >      here write common code 
        < div >   There is also common to write code
            
 
            {% block main_page%}   here is to inherit write the code template, from just behind main_page
 
            {% endblock%} 
        
       </ div > 
 </ div > 

< Script the src = "/ static / jQuery-3.3.1.js" > </ Script > 
< Script the src = "/ static / 3.3.7-on Bootstrap / JS / bootstrap.js " > </script>
</body>
</html>

 So we created a master, and that master how to use it? We create an index.html

{% Extends 'list / public_main.html'   %} inheritance master, note, use / foregoing list is a directory name
 
{%}% Block main_page 

      < div class = "C1" >    here to write their own code, would there between master code into two lines of code in the
 
{% endblock%}

note:

1. inherited code written in the first line

2. inherited the master's name must be enclosed in quotes

3. customized content written in block

4. The block defining a plurality of blocks, generally have js, css

 

to sum up:

{% Extends 'xxxx.html'%} master to inherit

By using the master {% block xxx %}to the definition of "block."

In the sub-pages correspond to replace the mother board by defining the contents of the corresponding block name in the motherboard.

Package

Take a look at the blog garden, above the navigation bar is not also every page, we can also put a navigation bar written in assembly, import other pages, is a component of HTML code

Xxx.html create a file, which is written some HTML code

Then in the master or other page references

{% include 'xxx.html' %}

The page content may be used, such as navigation, footer information components stored in a separate file, and then introduced as above syntax can be used where necessary.

Static related files

Earlier, we wrote css, js files are placed in the static directory, reference is as follows

<script src="/static/jquery-3.3.1.js"></script>

In front of the static file is setting.py value STATIC_URL

= STATIC_URL ' / static / '   # static HTML file in the folder using the prefix

But if one day, we need to change the value of a STATIC_URL, such as staticfile replaced, this time to put all references must be changed in staticfile

We can use {% load static%} to refer to a static file, then no matter how you change the static files do not change the rest of the code

Before the first look at the not modified

<!-- Bootstrap core CSS -->
<link href="/static/bootstrap-3.3.7/css/bootstrap.css" rel="stylesheet">

<!-- 当前页面用到的自定义样式 -->
<link href="/static/dashboard.css" rel="stylesheet">

<script src="/static/jquery-3.3.1.js"></script> <script src="/static/bootstrap-3.3.7/js/bootstrap.js"></script>

After the change, the string in the beginning do not need /, django will help us stitching, so we just change the value of STATIC_URL, you do not need to change the address to import static files

<!-- Bootstrap core CSS -->
<link href="{% static 'bootstrap-3.3.7/css/bootstrap.css' %}" rel="stylesheet">

<!-- 当前页面用到的自定义样式 --> <link href="{% static 'dashboard.css' %}" rel="stylesheet">

<script src="{% static 'jquery-3.3.1.js' %}"></script> <script src="{% static 'bootstrap-3.3.7/js/bootstrap.js' %}"></script>

Many were used in a file can be saved as a variable

{% load static %}
{% static "images/hi.jpg" as myphoto %}
<img src="{{ myphoto }}"></img>
get_static_prefix

 In the first html file to add the following two codes, what to see

{% load static %}
{% get_static_prefix %}

See the results with developer tools,

staticfile

The result is setting.py the value in STATIC_URL, and so, the above code we can write

<!-- Bootstrap core CSS -->
<link href="{% get_static_prefix %}bootstrap-3.3.7/css/bootstrap.css" rel="stylesheet">

<!-- 当前页面用到的自定义样式 --> <link href="{% get_static_prefix %}dashboard.css" rel="stylesheet">

<script src="{% get_static_prefix %}jquery-3.3.1.js"></script> <script src="{% get_static_prefix %}bootstrap-3.3.7/js/bootstrap.js"></script>

Both methods effect is the same, the first method is Django help us stitching and the second is our own stitching

simpletag

And similar custom filter, filter can only have a maximum of two parameters, but also a variable. The filter can accept more flexible parameters

from Django Import Template 

Register = template.Library ()   # fixed wording, generates a registration instance object 

@ register.simple_tag () 
DEF join_str (* args, ** kwargs):
     return  ' - ' .join (args)

Use simple tag in custom html in

% Load add_str%} {   <! - add_str py file name for the package under templatetags -> 

<! - use inside join_str function, are behind parameters -> < P > {% join_str 'Zou' ' IS '' the IT '= K1' Job '= K2' Bob '}% </ P >

Such display of results on the page is:

<p>zou-is-IT</p>

inclusion_tag

Some HTML snippet for return, the return of the dictionary format

Create a file in templatetags my_inclusion.py

from django import template

register = template.Library()


@register.inclusion_tag('page.html')  # 需要传一个文件名
def page(total, current_num):
    return {'total': range(1, total + 1), 'current_num': current_num}

page.html

{% for num in total %}
      {% if num == current_num %}
            <li class="active"><a href="#">{{ num }}</a></li>
      {% else %}
            <li><a href="#">{{ num }}</a></li>
      {% endif %}
{% endfor %}

The last function reference page in html pages

{% Load my_inclusion%}   import file name py 
{% page 6 3%}

Code explanation:

Page defines a function that takes two arguments, the above decorative requires a parameter file name, a dictionary is returned, this function is introduced in the page, pass two parameters, a 6, a is 3, after the page to get these two parameters, passed page.html rendering. Because in page 6 in the range, and then recycled, the result is 1 .... 6, making this judgment. He returned a page after rendering finish

to sum up:

csrf_token

  1 in form form

  2. Add a hidden input tag in the form

  name csrfmiddlewaretoken

  valve askjdaskdhashdkasd 64-bit string

 

Master inheritance

  1. Define a common master HTML code base.html

  2. Define the block in the master block

  3. subpage inherited master {% extends 'base.html'%}

  4. rewriting block block

  

  Note:
    1. the extends% { 'base.html'%} as the first line

    2. {% extends name%} name written inherited the master's name string

    3. customized content written in block

    4. The block defining a plurality of blocks generally have js css

 

Package

  1. Write a code nav.html

  2. {% include 'nav.html' %}

 

Static files related
  1. Load static% {%}

  2. {% static "relative path"%} - 'settings to acquire STATIC_URL' / static / 'and the relative path splicing

  3. {% get_static_prefix%} - " settings to acquire STATIC_URL '/ static /'

  "{%}% get_static_prefix relative path"

 

Custom inclusion_tag

  1. Create a templatetags in the app python package templatetags name can not be wrong

  2. Write py file in the package mytags

  3. Edit the file

    from django import template

    register = template.Library()


  4. Defined Functions

    We can accept parameters and return a dictionary

  5. Add function decorator

    @register.inclusion_tag('page.html')

  6. The function returns a dictionary to render xxx.html

  

 

Guess you like

Origin www.cnblogs.com/zouzou-busy/p/11181623.html