Django Framework Template Basics
Template use
The template basically consists of two parts, one is the HTML code, the other is the logic control code.
The realization of the logic control is composed of three parts basically:
1. Use of variables
{{person_name}}} #使用双大括号来引用变量
2. Use of Tag
{% if Ordered_warranty%} #使用大括号和百分号的组成来表示使用Django提供的
Template tag
{% for item in item_list%}
{{Item}}
{% ENDFOR%}
3. Use of filter
{{ship_date|date: "F J, Y"}},ship_date variable passed to data filter, data filter by using
The "F J, Y" parameters to format date data. "|" Represents a pipe operation in a Unix-like command.
Template system can not only cooperate with view, but also can be used independently.
The most basic way to use this is:
1. Create a template class using the template code string as a parameter
2. Create the contextual context object required in the template code, containing the values of each reference parameter required
3. Invoke the Template.render () method to render the template as a complete string.
>>> from Django Import template
>>> t = template. Template (' My name is {{name}}}. ')
>>> c = Template. Context ({' name ': ' Adrian '})
>>> print T.render (c)
>>> my name is Adrian.
You can also use the Dict index in template code, and then pass in the context to the desired dict
>>> from django.template Import template
>>> person = {' name ': ' Sally ', ' age ': ' 43 '}
>>> t = Template (' {{person.name}} ' is {{person.age}}} years old. ')
>>> C = Context ({"Person": person})
>>> T.render (c)
U ' Sally is the years old. '
You can also use functions, but only functions with no parameters
>>> from django.template Import template
>>> t = Template (' {{{var.upper}}---{{var.isdigit}}} ')
>>> T.render (Context ({' var ': ' Hello '})
U ' Hello--Hello--False '
You can also use a list index, but item.-1 is not allowed
>>> from django.template Import template
>>> t = Template (' Item 2 is {{items.2}}}. ')
>>> C = Context ({' Items ': [' apples ', ' bananas ', ' carrots ']})
>>> T.render (c)
U ' Item 2 is carrots. '
The above method of use is called the dot lookup method.
Issues to be aware of when using the Access function feature of DOT lookup:
1. When the function that executes in the template code throws an exception, it propagates to the upper layer until the exception has a parameter
Silent_variable_failure=true; In this case, the wrong function information is rendered into an empty string.
>>> class Silentassertionerror (Assertionerror):
... silent_variable_failure = True
>>> class PersonClass4:
... def first_name (self):
... raise Silentassertionerror
>>> p = PersonClass4 ()
>>> T.render (context ({The person: p}))
U ' my name is. '
2. Obviously, calling functions can produce some bad results, security vulnerabilities, and so on, if you have a bankaccout,
Then write {{account.delete}} in the template, so that when rendering, your account will be deleted ....
So to modify your delete function,
def delete (self):
# Delete the Account
Delete.alters_data = true# Indent no problem, take delete as an object and set its Alters_data property.
In this way, when rendering, it will become failed silent.
When the simple key value is not found in the rendering, it failed silent into an empty string instead of a fuss
Error.
>>> from django.template Import template
>>> t = Template (' Your name is {{name}} ')
>>> T.render (Context ())
U ' Your name is. '
>>> T.render (Context ({' var ': ' Hello '})
U ' Your name is. '
The context object can also be used to modify or delete operations.
>>> from django.template Import context
>>> C = Context ({"foo": "Bar"})
>>> c[' foo ']
' Bar '
>>> c[' newvariable ' = ' Hello '
>>> del c[' foo ']
>>> c[' foo ']
Use the Python manage.py Shell to start the Python Interactive command Line window with a general direct start Python self-brought
The difference between an interactive command line window is that the former will find a django_settings_module environment variable,
Tell Django to import settings.py configuration information.
The basic use of tag and filter
Tag
Use of {% if%}
You can use and, or, not to organize your logic. However, you do not allow both and and or conditional statements to appear.
Without the use of {% elif%}, multiple if statements can only be implemented with nesting.
{% if athlete_list%}
Here are the athletes: {{athlete_list}}.
{% Else%}
No athletes are available.
{% if not coach_list%}
Here are the coaches: {{coach_list}}.
{% ENDIF%}
{% ENDIF%}
Use of {% for%}
Used to cycle a list, you can also use the resersed keyword for reverse traversal, you can usually use the IF statement to first
Determine if the list is empty, iterate over it, and use the empty keyword to make a jump for the space.
{% for athlete in athlete_list resersed%}
{{Athlete.name}}}
{% EMPTY%}
There are no athletes. Only computer programmers.
{% ENDFOR%}
For tag also provides some built-in parameters to provide information about the template loop.
1. Forloop.counter current loop count, starting from 1
{% for item in todo_list%}
{{Forloop.counter}}: {{item}}
{% ENDFOR%}
2. Forloop.counter0 current loop count, starting from 0, standard indexing method
3. Forloop.revcounter the countdown count of the current loop, starting at the length of the list
4. Forloop.revcounter0 the countdown count of the current cycle, starting with the list length minus 1, the standard
5. forloop.first bool value to determine whether the first element of the loop
6. Forloop.last Ibid, judge is not the last element of the loop
7. Forloop.parentloop is used in a nested loop to get a reference to the parent loop, and then you can use the above parameters
{% for country in countries%}
- {% for City in country.city_list%}
- {% ENDFOR%}
Country #{{Forloop.parentloop.counter}} |
City #{{Forloop.counter}} |
{City}} |
{% ENDFOR%}
Ifequal and Ifnotequal, a look is the direct comparison of the value of the tag, requires two parameters, the use of more limited,
Limited to strings, integers, decimal comparisons, what lists, dictionaries, tuples not supported.
{% ifequal user CurrentUser%}
welcome!
{% ifequal section ' community '%}
Community
{% endifequal%}
{% endifequal%}
{#}, the use of annotations in a template can only be used on one line
If you want to use a multiline comment, use {% comment%}
{# This is a comment #}
{% Comment%}
This is a
Multi-line comment.
{% Endcomment%}
Filter
Filter is used for some simple processing of variables before they are displayed. Use a pipe-like operator ' | ', or you can do chain operations
{{Name|lower}}}
{{My_list|first|upper}}}
{{bio|truncatewords: ' 30}}}
Introduces several important filter:
Addslashes: Give any backslashes, single quotes, double quotes, plus a backslash. In the text contains
Javascript
Useful when it comes to strings.
Date: Used to format string information for data and Datatime objects.
{{pub_date|date: ' F J, Y '}}
Length: Returns the lengths of the variables.
Use template in view:
First, configure the path to the template file in settings.py.
Template_dirs = (
'/home/django/mysite/templates ',
)
Remember to use commas when remembering a path, which is to distinguish between a tuple or a block expression
You can also use the Python file path operation code when you set up:
Import Os.path
Template_dirs = (
Os.path.join (Os.path.dirname (__file__), ' Templates '). replace (' \ \ ', '/'),
)
Then, you can use the template in view
From Django.template.loader import get_template
From django.template Import context
From django.http import HttpResponse
Import datetime
Def current_datetime (
Request
):
now = Datetime.datetime.now ()
t = get_template (' current_datetime.html ')
HTML = T.render (context ({' Current_date ': now}))
return HttpResponse (HTML)
In most cases, you will use a shortcut method, Render_to_response () to do the above work.
From django.shortcuts import Render_to_response
Import datetime
def current_datetime (Request):
now = Datetime.datetime.now ()
Return Render_to_response (' current_datetime.html ', {' current_date ': now})
Tips for locals ()
If you have a lot of variables to pass to render, a construction dict element is cumbersome. Change the variable name directly to the variable name required in the template,
Then use the LOCASL () function, easy to handle
def current_datetime (Request):
Current_date = Datetime.datetime.now ()
Return Render_to_response (' current_datetime.html ', locals ())
Locals () returns the dict of the variable information in the local space, which can be passed directly to render, but one thing to note is that it returns the local variable
Information, some may not need to be used, such as request variables.
{%
Include
%} 's use
{% include ' nav.html '%}, used to introduce the contents of other templates, reduce duplicate template code
{% include Template_name%}, you can also use variable names
If the include template file is not found, when debug is true, the error templatedoesnotexist, when false, the page that piece for
Blank.
Admittedly, include can effectively reduce the duplicate code of the template. But one of the more elegant ways is:
Template inheritance.
First, create base.html
<title>{% block title%} {% Endblock%}</title>
My helpful timestamp site
- {% block content%} {% Endblock%}
- {% block footer%}
Visiting my site.
- {% Endblock%}
- We use a new tag,{% block%} to tell template engine, this section will quilt template
- To achieve. If the child template does not implement these sections, the code for the parent template is used by default.
- And then look at how the child template will be written:
- {% extends ' base.html '%}
- {% block title%} The current time{% Endblock%}
- {% block content%}
It is now {current_date}}.
- {% Endblock%}
- You only need to use {% extends%} to inherit the parent template, and then write the required content to the part that needs to be implemented.
- {% extends Template_name%} You can also use variable names to implement dynamic.
- Three-tier inheritance policy for template inheritance:
- 1. Create a base.html to set the appearance
- 2. For each part of the site, create base_section.html, such as base_phote.html, base_forum.html
- 3. Create your own templates for each page.
Django Frame Template Advanced Step
1. RequestContext function and Context processor
- First, we review how the template's View function is written:
- From django.shortcuts import Render_to_response
- DEF diary (Request):
- Return Render_to_response (' diary.html ', {' name ': ' QiQi '})
- To illustrate the convenience, we also give another way to write:
-->
From django.http import HttpResponse
to django.template Import Loader, context
def Diary (Request):
t = l Oader.get_template (' diary.html ')
c = Context ({' name ': ' QiQi '}) return
HttpResponse (T.render (c))
Perhaps some students do not understand, then I will give a third of the most stupid equivalent, we can skip directly back look:
From django.http import HttpResponse
to django.template Import template, Context
def Diary (Request):
Tin = Open ('./templates/diary.html ')
html = tin.read ()
tin.close ()
inf = {' name ': ' QiQi '}
t = Template (HTML)
c = Context (INF) return
HttpResponse (T.render (c))
In the above code, we use the context function for rendering.
As with the Django.template.Context function, there is also a django.template.RequestContext function that defaults to adding variables to the template, such as HttpRequest objects, current logged-in user information ......
Look at the following code:
From django.http import httpresponse from django.template import loader, Context Def view_1 (Request): # t = Loader.get_template (' template1.html ') c = context ({ ' app ': ' My app ', ' user ': request.user, ' ip_address ': request. meta[' REMOTE_ADDR '], ' message ': ' i am view 1. '  } ' return httpresponse (T.render (c)) Def view_2 ( Request): # t = loader.get_template (' Template2.html ') c = context ({ ' app ': ' My app ', ' user ': request.user, ' ip_address ': request. meta[' REMOTE_ADDR '], ' message ': ' i am the Second view. ' } return httpresponse (T.render (c))
where the three variables of app, user, and ip_address may need to be written repeatedly in the rendering of many templates, it's cumbersome. And by using the RequestContext function, we can simplify it like this:
From django.http import httpresponse from django.template import loader, RequestContext Def custom_proc (Request): return { ' app ': ' My app ', ' user ': request.user, ' ip_address ': request. meta[' REMOTE_ADDR ']  } def view_1 (Request): # t = loader.get_template (' template1.html ') c = RequestContext (request, {' message ': ' i am view 1. '}, [custom_proc])
return httpresponse (T.render (c)) def view_2 (Request): # t = loader.get_template (' template2.html ') c = requestcontext (Request,&nbsP {' message ': ' I am the second view. '}, [custom_proc]) Return httpresponse (T.render (c))
Where we write the function Custom_proc, called the context processor. In terms of terminology, we use the RequestContext function and the context processor to simplify the code that uses the template.
and use render_to_response on this basis, we can also simplify it to:
From django.shortcuts import render_to_response from django.template import RequestContext Def custom_proc (Request): return { ' app ': ' My app ', ' user ': request.user, ' ip_address ': request. meta[' REMOTE_ADDR ']  } def view_1 (Request): # return render_to_response (' template1.html ', {' message ': ' i am view 1. '}, context_ Instance=requestcontext (Request, [custom_proc]) def view_2 (request): # ... return render_to_response (' template2.html ', {' message ': ' I am the second view. '}, context_instance= RequestContext (Request, [custom_proc])
At this point, there is a bit of a flaw in the rendering statement, each time you need to manually assign values to the processors.
Django provides support for the global context processor--allowing you to list some of the session processors in global variables, which Django will automatically add to every time you call the RequestContext function. This global variable can be found in the templates parameter, and its default value is:
# templates parameter, in the ' OPTIONS ' dictionary, ' context_processors ' list
[
' Django.template.context_processors.debug ',
' Django.template.context_processors.request ',
' Django.contrib.auth.context_processors.auth ',
' Django.contrib.messages.context_processors.messages ',
]
These four values are not much said, you can go to search books and manuals. At this point, we can further simplify the code as follows:
From django.shortcuts import render_to_response from
django.template import RequestContext
def view_1 (Request ):
# ...
Return Render_to_response (' template1.html ',
{' message ': ' I am View 1 '},
CONTEXT_INSTANCE=REQUESTC Ontext (Request))
def view_2 (Request):
#
... Return Render_to_response (' template2.html ',
{' message ': ' I am ' second view.},
Context_instanc E=requestcontext (Request))
As for the context processor, it should be written in a separate code, recommended as context_processors.py.
Just put the code in the Python search path and Django can find it. It is recommended to put it in the directory of Project or app.
# context_processors.py
def custom_proc (Request): Return
to {' app ': ' My app ',
' user ': RE Quest.user,
' ip_address ': request. meta[' REMOTE_ADDR ']
}
Finally, you can modify the global variable to:
[
' Context_processors.custom_proc ',
]
2. html Automatic escape
When you generate HTML from a template, there is always a risk that the variable contains characters that affect HTML.
The book cited a small example, here without repeating, directly said the solution:
1. Make sure that every untrusted variable is filtered using the escape filter to convert potentially harmful HTML characters to harmless. This is the first years of Django's processing strategy.
2. Automatically escape with Django HTML. This method is described below.
As long as you use the Django template, the following five characters in the variable label will be automatically escaped:
Original character escape result
< <
> >
' '
" "
& &
Of course, sometimes you will use template variables to write a piece of HTML code, then you need to turn off automatic escape, the closing method is as follows:
1. Variable level, with safe filter: This is not to be escaped: {{Data|safe}}
2. Template level, with autoescape tags: {% autoescape off%} ... {% Endautoescape%}
There are two states of this label: off, on.
This tag can be nested, for example, you can insert a label on a off label that is nested on.
When you use a template to inherit, it is obvious that the tag will continue to take effect.
3. Site level, this book only said there are methods, but did not write, temporarily doubt.
Attention:
1. Filter multiple times and filter once effect exactly the same.
2. String constants in the template, such as constants contained in the filter, escape from automatic escaping, and the strings in the variable do not.
{{data|default: ' 3 < 2}}}
{{data|default: ' 3 < 2 '}} <--bad! Don ' t does this.
Doubt:
1. What is the escape filter? As it is written in the document, it seems to refer specifically to the Autoescape label?
3. How Django loads the template
3.1 What is engine
Engine, simple is about the template of a set, the specific definition here is not introduced, you can go to the beginning of the article to the document to view, later have time will fill.
Load the template at ordinary times, using the default Engine object in Django, which is the templates parameter we have in settings.py. As a result, you load the template in the default way, which is equivalent to loading the template with the default Engine object in Django. This object is: django.template.engines[' Django '
And if you want to instantiate another Engine object, you need to use this definition: Django.template.Engine ()
3.2 Statement to load template
There are three of the statements in the Django load template:
1. engine.from_string (Template_code)
According to the engine object's settings, compile the given code generation template and return a template object.
# method One, using the default engine
From django.template Import engines
Template = engines[' Django '].from_string (Template_code)
# method Two, using an empty engine (no context_processors or something like that)
From django.template import Engine
Template = Engine (). from_string (Template_code)
2. Engine.get_template (Template_name)
According to the engine object, find the template based on the given name, compile internally, and finally return a template object.
If the template does not exist, a templatedoesnotexist exception is returned.
3. Engine.select_template (self, template_name_list)
According to the engine object's settings, based on the given list of names, search for the template sequentially, the first to find the same processing, return a template object.
If none exists, a templatedoesnoeexist exception is returned.
3.3 Template Loader
We've always said that in the load template, but the templates parameter does not have the loader's settings, we are using the default loader in Django all the time.
Next, we'll introduce the template loader in Django:
1. Django.template.loaders.filesystem.Loader (default)
Loads the template from the file system.
Path: The ' dirs ' list in the template parameter.
2. Django.template.loaders.app_directories. Loader
Loads the template from the file system.
Path: Each app, or Installed_apps parameter, is the Templates folder in each app directory.
Open mode: Set the ' App_dirs ' in the templates parameter to True.
3. Django.template.loaders.eggs.Loader
Load the template from the Python egg.
Path: each app.
Open mode: Write similar code (untested, for reference only)--
TEMPLATES = [{
' backend ': ' django.template.backends.django.DjangoTemplates ', '
dirs ': [Os.path.join (Base_di R, ' templates ')],
' OPTIONS ': {
' loaders ': [
(' Django.template.loaders.eggs.Loader '),
],
},
}]
4. Django.template.loaders.cached.Loader
When you load a template, the first time the loader loads the template and caches it, and then loads the template directly from the cache.
Path: Depends on the loader of the call.
Note: The actual loaded templates should ensure that their nodes are process security (THREAD-SAFE), as detailed in the documentation.
Open mode: Write similar code (originating from document)--
templates = [{ ' backend ': ' Django.template.backends.django.DjangoTemplates ', ' dirs ': [os.path.join (Base_dir, ' templates ')], ' OPTIONS ': { ' Loaders ': [ (' Django.template.loaders.cached.Loader ', [ ' Django.template.loaders.filesystem.Loader ', ' Django.template.loaders.app_directories. Loader ', ], ], },}]
5. Django.template.loaders.locmem.Loader
Loading a template from a Python dictionary is often used for testing.
Doubt: The actual effect has not been tested, it is not very understandable.
Open mode: Write similar code (originating from document)--
TEMPLATES = [{
' backend ': ' django.template.backends.django.DjangoTemplates ', '
OPTIONS ': {
' loa DERs ': [
(' Django.template.loaders.locmem.Loader ', {
' index.html ': ' Content here ',
}),
],
},
}]
In fact, books and documents also mention how to write your own templates, the two classes used in the template for debug, and how to write templates in a standalone model ...
But because it is not used for a while, so do not write, and later used to supplement.