Template system for the Django Learning series

Source: Internet
Author: User

First, the template label

If/else

{% if%} tags check if the value of one variable is true or equal to another value, if true, the system executes a block of code between {% if%} and {% endif%}, for example:

if today_is_weekend%}    <p>welcome to the weekend!</p>{% endif%}

{% Else%} tag is optional, if not true the code block between {% Else%} and {% endif%} is executed

Note: Be sure to close each {% if%} code block with {% ENDIF%}

For

{% for%} allows us to iterate over a sequence, similar to the case for a Python for statement, which is the for X in Y Y sequence of iterations to iterate over and the X name of the variable used in each particular loop. In each iteration, the template system renders { % for % } { % endfor % } Everything between and, for example:

 for  in athlete_list   %}    <li>{{athlete.name}}</li>{% endfor%}

forloop

Second, template inheritance

Concept:

Template inheritance is the first to build a skeleton template framework, and then the other child templates inherit the base template

Example

Define urls.py

 from Import URL  from Import Admin  from Import  = [    url (r'^assets/', views.assets),    URL (r  '^user/', Views.user),]

Define views.py

defAssets (Request): Assets_list= []     forIinchRange (10): Temp= {'Host':'Host'+str (i)} assets_list.append (temp)returnRender (Request,'assets.html',{'assets_list': assets_list})defUser (Request): User_list= []     forIinchRange (5): Temp= {'User':'Alex'+str (i)} user_list.append (temp)returnRender (Request,'user.html',{'user_list': User_list})

Defining the base template (layout.py)

<! DOCTYPE html>"en">"UTF-8"> <title>Title</title> <style>. PG-header{height:48px; Background-Color:cadetblue; }. PG-body{min-height:500px; }. PG-body. body-menu{Width:20%;        Float:left; }. PG-body. body-content{Width:90D;        Float:left; }. PG-footer{height:100px; Background-Color:brown; }. active{Background-Color:aquamarine;        Color:white; }    </style>class="Pg-header">Backend System V1</div> <divclass="Pg-body"> <divclass="Body-menu"> <ul> <li><a id="Assets"href="/assets"> Asset Management </a></li> <li><a id="Assets"href="/user"  > User Management </a></li> </ul> </div> <divclass="body-content">             {% block Body%}{% Endblock%} #这里表示子模板继承该模板之后, the value here is covered by the values in the quilt template
</div> </div> <divclass="Pg-footer"></div></body>

Define a child template (user.html)

' layout.html ' %}              #引用layout. html Template {% block body%}                         #这里表示覆盖掉基础模板中block part    of body <ul >    {for in user_list%}        <li>{{item.user}}</li >    {% endfor%}    </ul>{% endblock%}

Define a child template (assets.py)

' layout.html ' %}                #引用layout. html Template {% block body%}                           #这里表示覆盖掉基础模板中block part     of body <ul>     {for in assets_list%}        <li>{{item.host}}</li>     {% endfor%}    </ul>{% endblock%}

Effect Show

Test: Modify "backend system V1" to "backend system V2" in the motherboard (base template), then change in two sub-templates

How template Inheritance Works

When loading the user.html and assets.html templates, the template engine discovers the {% extends%} tag, noting that the template is a child template, and the template engine immediately loads its parent template, that is, in this case layout.html

At this point, the template engine notices a {% block%} label and replaces the block with the contents of the child template, and the template engine will use what we defined in {% block body%}

Template inheritance common three-layer method

    1. Create base templates (Master templates), where you define the appearance of the site, which are infrequently modified or never modified
    2. Create sub-templates for each area of the site that extend their base template (the parent template),
    3. Create separate templates for each type of page, such as forum pages or photo galleries, which expand the appropriate area templates

This approach maximizes the reuse of code and makes it easy to add content to public areas such as zone-level navigation

Here are some tips for template inheritance:

  • If used in a template { % extends % } , it must be marked as the first template in the template, otherwise, the template inheritance will not work;
  • In general, the more labels in the base template, the better { % block % } , remember that the child template does not have to define all the code blocks in the parent template, so you can populate some blocks of code with reasonable defaults, and then define only the code blocks that are required for the child template. As the saying goes, the more hooks the better;
  • If you find yourself copying code between multiple templates, you should consider placing the snippet in one of the parent templates { % block % }
  • If you need to access the contents of a block in the parent template, use this tag to display the contents of the parent template, which is very useful if you want to add content instead of overloading the upper block of code.
  • It is not allowed to define multiple names in the same template { % block % } , because the block label works in both directions, that is, the block tag not only digs a hole to fill, but also defines what the pit fills in the parent template. If two labels with the same name appear in the template { % block % } , the parent template will have no way of knowing which block's content to use;

  • { %The extends % } same load method is used for the passed-in template name get_template() . That is, the template name is added TEMPLATE_DIRS after the setting;

  • In most cases, { % extends % } The argument should be a string, but if the parent template name can be determined by the runtime, this parameter can be a variable, which allows you to implement some cool dynamic functions;

Template system for the Django Learning series

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.