Django Book Learning notes-Templates

Source: Internet
Author: User

1. Basic knowledge of template system

A template is a text that separates the representation and content of a document. The template defines the placeholder and various basic logic (template tags) that are used to standardize how the document should be displayed. Templates are often used to generate HTML, but Django templates can also produce any document based on text format.

2. How to use the template system

The most basic way to use a Django template in Python code is as follows:

1). You can create a template object with the original templates code string, and Django also supports the creation of template objects in a way that specifies the path to the templates file;

2). Call the Render method of the template object and pass in a set of variable context. It will return a template-based presentation string, and the variables and tags in the template will be replaced by the context value.

Cases:

>>> from django import template>>> t = template. Template (' My name is {{name}}}. ') >>> c = Template. Context ({' name ': ' Adrian '}) >>> print T.render (c) My name is adrian.>>> c = template. Context ({' name ': ' Fred '} ') >>> print T.render (c) My name is Fred.

3. Finding the background variable

The key to traversing complex data structures in a Django template is the period character (.).

For example, suppose you want to pass a Python dictionary to a template. To access the dictionary's values through a dictionary key, you can use a period:

>>> from django.template Import template, context>>> person = {' name ': ' Sally ', ' age ': '}>>> ' ; t = Template (' {{person.name}} is {{person.age}}} years old. ') >>> C = Context ({' Person ': "Person}") >>> T.render (c) U ' Sally is years. '

Similarly, you can access the properties of an object through a period. Point syntax can also be used to refer to an object's methods. Finally, the period can also be used to access the list index.

The period lookup rule can be summarized as follows: When the template system encounters a point in the variable name, try to find it in the following order:

    • Dictionary type lookup (e.g. foo["bar"] )

    • Property lookup (e.g. foo.bar )

    • method invocation (e.g. foo.bar () )

    • List type index lookup (e.g. Foo[bar] )

The system uses the first valid type found. This is a short-circuit logic.

Note : You do not need to use parentheses when calling a method, and you cannot pass arguments to the method; You can only invoke methods that do not require arguments.

4. Basic template tags and filters

1). If/else:{% if %} label check (evaluate) A variable, if the variable is true (that is, the variable exists, non-empty, not Boolean false), the system will be displayed in the {% if %} and {% endif %} any content, for example:

{% if today_is_weekend %}    <p >welcome to the weekend!</p>{% else %}    <p>get  back to work.</p>{% endif %} 

{% if %} The tag accepts the and, or or not keywords to make judgments on multiple variables, or to negate (not ) a variable, but {% if %} tag does not allow both and and or in the same label, because it is logically possible to blur. And without the {% elif %} tag, use the nested {% if%} tag to achieve the same effect. Be sure to use {% endif %} to close each of the {% if %} tags.

2). For

{% for %} Allows us to iterate over a sequence. In each cycle, the template system renders at {% for %} and {% endfor %} All the content between.

Adding a reversed to the label causes the list to be iterated backwards.

{% for athlete in athlete_list reversed%} ... {% ENDFOR%}

The for tag supports an optional {% empty%} clause through which we can define the output content when the list is empty.

{% for athlete in athlete_list%} <p>{{athlete.name}}</p>{% empty%} <p>there is no athletes. Only computer programmers.</p>{% endfor%}

In each {% for%} loop there is a template variable called Forloop. This variable has some properties that indicate looping progress information.

Forloop.counter is always an integer counter that represents the number of executions of the current loop. This counter starts at 1, so the forloop.counter will be set to 1 at the first loop.

{% for item in todo_list%} <p>{{Forloop.counter}}: {{item}}</p>{% endfor%}

Forloop.counter0 is similar to forloop.counter , but it is counted from 0. The first time the loop is executed, this variable is set to 0.

forloop.revcounter is an integer variable that represents the remainder of the loop. When the loop is first executed, Forloop.revcounter is set to the total number of items in the sequence. In the last loop execution, this variable will be set to 1.

Forloop.revcounter0 is similar to forloop.revcounter , but it takes 0 as the end index. The first time the loop is executed, the variable is set to the number of items in the sequence minus 1.

Forloop.first is a Boolean value. This variable is true for the first time the loop is executed, which is useful in the following scenario.

{% for object in objects%} {% if Forloop.first%}<li class= "First" >{% else%}<li>{% endif%} {{object}} </li>{% endfor%}

Forloop.last is a Boolean value that is set to True when the loop is last executed. A common use is to place pipe breaks between a series of links (|)

{% for link in links%} {{link}} {% if not forloop.last%} | {% ENDIF%} {% ENDFOR%}

Forloop.parentloop is a reference to the Forloop object of the previous loop of the current loop (in the case of nested loops).

3). ifequal/ifnotequal

{% ifequal %} The label compares two values when they are displayed in {% ifequal %} and {% endifequal %}< all the values in the/c11>. Similar to {% if %} , {% ifequal %} The optional {% else%} tag is supported.

{% ifequal section ' sitenews '%} 

Only template variables, strings, integers, and decimals can be used as parameters of the {% ifequal %} tag.

{% ifequal variable 1%} {% ifequal variable 1.23%} {% ifequal variable ' foo '%} {% ifequal variable "foo"%}

Some other types, such as the dictionary type for Python, the list type, and the Boolean type, cannot be used in {% ifequal %} . Here are some examples of errors :

{% ifequal variable True%} {% ifequal variable [1, 2, 3]%} {% ifequal variable {' key ': ' Value '}%}

5. Notes

The Django template language also provides code annotations. Annotations Use {# #}, but comments of this syntax cannot span multiple lines :

{# This is a comment #}

If you want to implement multiple lines of comments, you can use the {% comment%} template label, like this:

{% Comment%} This is amulti-line comment. {% Endcomment%}

6. Filter

A template filter is a simple way to modify the value of a variable before it is displayed. The filter uses the pipe character as follows:

{{Name|lower}}

The following are a few of the most important filters.

addslashes : Adds a backslash to any backslash, single quotation mark, or double quotation mark before.

Date : Formats a date or datetime object by the specified format string parameter.

Length: Returns the lengths of the variables. For a list, this parameter returns the number of list elements. For a string, this parameter returns the number of characters in the string. You can use this method for a list or string, or for any Python object that knows how to measure the length (that is, an object with the __len__ () method).

7. Using a template in a view

1). Template loading

Open the settings.py configuration file and locate Template_dirs to add a directory to hold the template file, for example:

Template_dirs = ('/home/django/mysite/templates ',)

After you complete the template_dirs Setup, the next step is to modify the view code so that it uses the Django template load feature instead of hard-coding the template path. Cases:

From Django.template.loader import get_templatefrom django.template import contextfrom django.http Import Httpresponseimport datetimedef Current_datetime (Request): now = Datetime.datetime.now () t = get_template (' Current_da tetime.html ') HTML = T.render (Context ({' Current_date ': now}) return HttpResponse (HTML)

The get_template () method automatically connects you with the template_dirs directory you have set up and the template name parameter you passed in the method, finds the location of the module in the file system, opens the file, and returns a compiled Template object.

2). Render_to_response ()

Django provides a quick way to load a template file, render it, and return it as a httpresponse . The shortcut is a function named render_to_response () in the django.shortcuts module.

The first parameter of render_to_response () must be the name of the template to use. If you want to give the second argument, the argument must be the dictionary that is used to create the Context for the template. If you do not provide a second argument, render_to_response () uses an empty dictionary.

From django.shortcuts import render_to_responseimport datetimedef current_datetime (Request): now = DATETIME.DATETIME.N ow () return render_to_response (' current_datetime.html ', {' current_date ': now})

8.include Template Label

This tag allows the content of other templates to be included in the (template). The parameter of the label is the name of the template to be included, either a variable or a hard-coded string in single/double quotation marks. Whenever the same code appears in multiple templates, you should consider whether you want to use {% include %} to reduce duplication.

# mypage.html

9. Template inheritance

Template inheritance is to construct an underlying framework template, and then overload it with the common parts of the site and the definition blocks in its child templates.

 #base. html<! doctype html public  "-//w3c//dtd html 4.01//en" >

We use a template tag that we've seen before: {% block %} . All {% block %} tags tell the template engine that child templates can overload these parts. Each {% block %} label is to tell the template engine that this piece of content under the template will likely be overwritten by the quilt template.

#current_datetime. html {% extends "base.html"%}{% block title%}the current time{% endblock%}{% block content%}<p> ; It's now {{current_date}}.</p>{% endblock%}

When loading current_datetime.html template, the template engine found {% extends %} tag, notice that the template is a child template. The template engine immediately mounts its parent template, base.html .

At this point, the template engine takes note of the three {% block %} tags in base.html and replaces the blocks with the contents of the child template. Therefore, the engine will use the title that we defined in { block title %} for the {% block content %} is also true. Therefore, the page title piece will be replaced by {% block title %} , similarly, the content of the page will be set by {% block content %} is replaced.

Here are some tips for using template inheritance:

    • If you use {% extends %} in the template, you must ensure that it is the first template tag in the template. Otherwise, template inheritance will not work.

    • In general, the more tags in the base template are {% block %} , the better. Remember that the child template does not have to define all the code blocks in the parent template, so you can populate some blocks 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 a {% block %} of the parent template.

  • If you need to access the contents of a block in the parent template, use the {{ block.super }} tag, which will show the contents of the parent template. This variable is useful if you want to add content only to the upper block of code, not all overloads.

  • Multiple {% block %} with the same name cannot be defined in the same template. This limitation exists because the block label works in both directions. In other words, the block tag not only digs a hole to fill, it also defines what is filled in the pit in the parent template. If two {% block %} tags of the same name appear in the template, the parent template will have no way of knowing what block to use.

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

    • In most cases, the parameter of{% extends %} should be a string, but this parameter can be a variable if the parent template name is determined until the runtime. This allows you to implement some cool dynamic features.


Django Book Learning notes-Templates

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.