Crazy Summer School Django Learning notes (ii)--template
Reference: "The Django book" chapter fourth
basic knowledge of template
1. How the template works
Start the interactive interface with the Python manage.py shell (because manage.py saves the Django configuration, if you run the following code directly from the Python startup interface)
Enter the following code
>>> from Django Import template
>>> t = template. Template (' My name is {{name}}}. ')
>>> c = Template. Context ({' name ': ' Zhengkai '})
>>> print T.render (c) I
name is Zhengkai.
Finally, displays the My name is Zhengkai.
Explain:
t = template. Template (' My name ' {{name}}}. ') creates a Template object
c = Template. Context ({' name ': ' Zhengkai '}) Creates a context object to hold the mapping relationship in the Template object. Its constructor is a dictionary.
T.render (c) T is rendered with C to return a Unicode object
2. Variable
In the example above, the context passes a simple string. However, the template system can also handle more things, such as lists, dictionaries, custom objects, and so on.
List:
>>> from django.template import template,context
>>> t = Template (' Item 2 ' {{items.2}} ')
;>> C = Context ({' Items ': [' apples ', ' bananas ', ' carrots ']})
>>> print T.render (c)
Item 2 is Carrots
Dictionary:
>>> person={' name ': ' Sally ', ' age ': '% '}
>>> t = Template (' {{person.name}}} ' is {{person.age}}} years old. ')
>>> C = Context ({' Person ':p Erson})
>>> print T.render (c)
Sally was years old.
Object properties:
>>> import datetime
>>> d = datetime.date (2014,7,3)
>>> d.year
2014
> >> d.month
7
>>> d.day
3
>>> t = Template ("The date is {date.year}}/{{ Date.month}}/{{date.day}}. "
>>> C = Context ({' Date ':d}]
>>> print T.render (c) The
date is 2014/7/3.
Object method:
>>> class A:
... def getName (self):
... Return to ' Sally '
...
>>> a = A ()
>>> a.getname ()
' Sally '
>>> t = Template (' name is {{a.getname}} ')
>>> c = Context ({' A ': A})
>>> print T.render (c)
name is Sally
Object method Note: You do not have to write () or write parameters
Multilevel depth nesting:
>>> person={' name ': ' Sally ', ' age ': ' $ '}
>>> t = Template (' {{person.name.upper}} ')
> >> C = Context ({' Person ':p Erson})
>>> print T.render (c)
SALLY
3. How to handle invalid variables
By default, if a variable does not exist, the template system will show it as null and do nothing.
4. Context Object
The context object is much like a dictionary and can be added and deleted like a dictionary
>>> C = Context ({' name ': ' Sally '} ')
>>> c[' name ']
' Sally '
>>> c[' age ' = ' 23 '
>>> c[' age ']
'
>>> del c[' age '
[>>> c[' age ']
traceback (most Recent call last):
File "<console>", line 1, in <module>
File "/usr/lib64/python2.7/ site-packages/django/template/context.py ", line, in __getitem__
raise Keyerror (Key)
keyerror: ' Age '
5. Basic template label and filter
If/else
Example:
{%if Today_is_weekend%}
<p>welcome to the weekend!</p>
{% endif%}
{%if Today_is_weekend%}
<p>welcome to the weekend! </p>
{% Else%}
<p> get work. </p>
{% endif%}
Determine if the variable after if is true or false. Empty list [], null tuple (), empty Dictionary {}, empty string ', 0,none,false are considered false
{%if%} tag also accepts and, or, or not
{%if athlete_list and coach_list%}
Both athletes and coaches are available
{% ENDIF%}
And not together
{%if athlete_list and not coach_list%}
There are some athletes and avsolutely not coaches.
{% ENDIF%}
Multiple and together or multiple or can be connected to use
{%if athlete_list and not coach_list and cheerleader_list%}
But and and or cannot be used concurrently
As the following is the wrong
{%if athlete_list and coach_list or cheerleader_list%}
for
<ul>
{% for athlete in athlete_list%}
<li>{{althete.name}}</li>
{% endfor%}
</ Ul>
You can also add the {% empty%} tab, and when the defined list is empty, the contents after {% empty%} are run
<ul>
{% for athlete in athlete_list%}
<li>{{althete.name}}</li>
{% empty%}
<p >there are no athletes.</p>
{% endfor%}
</ul>
Django does not support Continue,break
Each {% for%} loop has a Forloop variable that holds information about the progress of the loop. Can only be used in loops, {% endfor%} is not available after
{{Forloop.counter}}: Counting from 1, indicating the number of times the current loop has been executed
{{FORLOOP.COUNTER0}}: is approximately the same as {{forloop.counter}}, but is counted starting from 0
{{Forloop.revcounter}}: Indicates the number of times the loop has been left
{{FORLOOP.REVCOUNTER0}}: Count starting from 0
{{Forloop.first}}: A Boolean value that is true if the first loop is False
{{Forloop.last}}: A Boolean value that is true if it is followed by a loop or False
{{Forloop.parentloop}}: is a reference to a Forloop object that points to the previous hit loop of the current loop (when nested loops)
ifequal/ifnotequal
{% ifequal%} is like {%if%} but it is used to determine whether the following 2 variables are the same. Same execution.
{%ifnotequal%} is not the same as Ifequal
{% ifequal user currentuser%}
You can also add the {% Else%} label
{% ifequal secton ' sitenews '%}
Only template variables, strings, integers, and small trees can be used as parameters for {% ifequal%} tags
Annotations
Django template annotations with {#}
For example
{# This is a comment #}
Multi-line annotation
Use {% Comment%} label
For example:
{% Comment%}
This is a
Multi-line comment.
{% Endcomment%}
Filter |
For example
{{Name|lower}}}
Convert uppercase to lowercase
Filters can be nested using
Such as
{{My_lsit|first|upper}}}
Some filters have parameters,
Such as
{bio|truncatewords: "30"}
Show variable bio Top 30 words
Some of the most important filters
Addslashes: Adds a backslash to the front of any backslash, single or double quotation mark. This is useful when working with text that contains JavaScript.
Date: Ali specifies format string parameter format date or DateTime object
Such as
{{pub_date|date: ' F J, Y '}}
Length: Returns the lengths of the variables. For a list, returns the number of elements in the list. For a string, returns the number of characters in the string. (But you can also use __len__ () to return the length)
ii. using templates in the View
Can do this
From django.http import HttpResponse
to django.template Import template, Context
import datetime
def Current_datetime (Request): Now
= Datetime.datetime.now ()
t = Template ('
But the code above, the template is still embedded in Python, to improve:
From django.http import HttpResponse
to django.template Import template, Context
import datetime
def Current_datetime (Request): Now
= Datetime.datetime.now ()
fp = open ('/test/www/mysite/templates/ Mytemplate.html ')
t = Template (Fp.read ())
c = Context ({' Current_date ': now})
HTML = T.render (c)
return HttpResponse (HTML)