Django-- template

1. What is a template?

  Html template file that is used for the response, the page design and Python code much cleaner separation easier to maintain. We can use Django's  template system  (Template System) to implement this model, which is the problem to be discussed in detail in this chapter.

2, the variable template syntax

  Methods to render the dictionary variable manner with the view spread function template, the template can then {{ 'variable name'}} reference variable.

  views:

def index(request):

    name = 'alex'
    age =22
    students = ['alex', 'taibai', 'nvshen']
    
    return render(request, 'index.html',{'name':name, 'age':age, 'students':students}

  The key name of the key can set their own 

  templates:

<body> 
    <the p-> name {name}} {</ the p-> 
    <the p-> Age {{age}}-year-old </ the p-> 
    <the p-> Student students.0}} {{</ the p->   # this way index by extracting a certain element in the list 
    <p> student students.1} {} {</ P> 
</ body>

  If you need to pass a lot of variables, write one by one to render in less convenient, so use the locals () method,

def index(request):

    name = 'alex'
    age =22
    students = ['alex', 'taibai', 'nvshen']
    into = {'name':'alex', 'age': 100, 'gender': 'other'}
    return render(request, 'index.html', locals())

  This allows you to pass in all the variables.

3, the filter template

  The specific format of the variable {{| Filter: Parameter}}

  default: If a variable is false or empty, the default values ​​given. Otherwise, use the value of the variable. E.g:

<P> {{book_list1 | default: ' No matching books ' }} </ P>

  length: length of the return value. It works both strings and lists. E.g:

{{ list|length }}

  filesizeformat:将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB''4.1 MB''102 bytes', 等等)。例如:

{{ fail_size|filesizeformat }}

  date: The conversion time required format. E.g:

  views:

 value=datetime.datetime.now()

  templates:

{{ value|date:"Y-m-d" }} 

  can also be:

{{ value|date:"Y/m/d" }} 

  slice: string sections. E.g:

{{ value|slice:"2:-1" }}

  truncatechars: If the string of characters is more than a specified number of characters, it will be truncated. Translatable strings will be truncated sequence at the end of the ellipsis ( "..."). E.g:

  views:

shi = 'When you are old and grey and full of sleep, And nodding by the fire,take down this book, And slowly read,and dream of the soft look '

  templates:

<p>{{ shi|truncatechars:5 }}</p>

  Results: whe ...

  Note: ... should occupy three bytes position.

  safe: Django for security, automatically translating various labels, but sometimes we hesitate to his translation, we need a safe. E.g:

  views :( directly into the variable, generate a string at the interface, the filter must be added safe, in order to generate a tag a)

link = "<a href= 'http://www.baidu.com'>点我</a>"

  templates:

 <p>{{ link|safe }}</p>

 

4, the template tag

for tag: through each element. E.g:

{% for person in person_list %}
    <p>{{ person.name }}</p>
{% endfor %}

  Dictionary is also available.

{% for key,val in dic.items %}
    <p>{{ key }}:{{ val }}</p>
{% endfor %}

  tab for travel its own methods.

  forloop.counter: This generation is the first element several cycles get.

{% for book in book_list %}
        <li>{{ forloop.counter }} {{ book }} </li>
    {% endfor %}

  forloop.counter0: as above, but change from zero.

  forloop.revcounter: turn

  forloop.revcounter0: turn from scratch

  forloop.first: Analyzing this element is not the first cycle obtained, if the display is True.

  forloop.last: Analyzing this element is not obtained in the last cycle, then the display is False.

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

{% for person in person_list %}
    <p>{{ person.name }}</p>

{% empty %}
    <p>sorry,no person here</p>
{% endfor %}

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

{% IF NUM> 100 or NUM <0% }
     <P> Invalid </ P> 
{ % elif NUM> 80 and NUM <100% }
     <P> Elite </ P> 
{ % the else % }
     <P> Minato live it </ P> 
{ %} endif%

  for the label can be set if tags:

{% for person in person_list %}
    {% if person.age > 900 %}
        <p>{{ person.name }} {{ person.age }}</p>

    {% endif %}

{% endfor %}

with Tags: Use a simple name cache a complex variable , when you need to use a method (such as database access) many times when it is very useful.

{% with name=person_list.2.name  %}
    <p>{{ name }}</p>
    {% endwith %}

  This put person_list.2.name change in the presence name, do not always look for such a complex.

csrf_token Label: The label is used to protect the cross-site request forgery, which generates a token, for user authentication.

5, inherited template

  If we have a general framework of multiple pages are the same, just different where the individual label, if every page we will write out all of the template, there will be a lot of duplication of code, so this time, for brevity code, we can use these repetitive code into a file for use inherit other templates, this file is called the master.

  In the master, there are specific places for other sub-template add tags, known as box (hook) - Blocks.

  Template base.html

<div class = " COL-MD-. 9 " > 
                { % Block contend% }
                     <H3> WELCOM </ H3> # subpalette If no content, the content here is returned, the sub-template, if the content, the cover where Content. 
                { % Endblock% }
  </ div>

  Sub-template index.html

{% extends 'base.html' %}


    <div class="jumbotron">
                  <h1>Hello, world!</h1>
                  <p>...</p>
                  <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
                </div>
{% endblock %}

  Here with {% extends %} labels to tell the system that his master is base.html, index.html page when accessing the system, back to the first orientation to base.html, Note: The {% extends %} label must be the first line in the sub-template.

  In the master plurality of boxes may be provided, and better.

  If you need to display the contents of the box and the sub-template, you can use {{block.super}} tag,

{% extends 'base.html' %}


{% block contend %}
    {{ block.super }}

    <div class="jumbotron">
                  <h1>Hello, world!</h1>
                  <p>...</p>
                  <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
                </div>
{% endblock %}

  For better readability, you can also give your  {% endblock %} tag a  name  . E.g:

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

  A plurality of the same name can not be defined in a template  block tag.

 

  

 

    

 

 

  

Guess you like

Origin www.cnblogs.com/490144243msq/p/11575994.html