Document directory
A template consists of two parts: HTML code and logic control code. The implementation of logical control consists of three parts: 1. variable use {person_name }}# use double braces to reference variable 2. tag {% if ordered_warranty %} # use braces and percent signs to indicate that
Template tag {% for item in item_list %} <li >{{ item }}</li >{% endfor %} 3. use the {ship_date | date: "F j, Y" }}and ship_date variables of the filter to the data filter. Use the "F j, Y "to format the date data. "|" Indicates pipeline operations similar to those in Unix commands. The Template system can not only work with the view, but also be used independently. The basic usage is: 1. use the Template code string as the parameter to create a Template class 2. create the Context object required in the template code, including the value of each required reference parameter 3. call Template. render () method, rendering the template into a complete string. >>>
FromDjango
ImportTemplate
>>> T = template. Template ('My name is {name }}.')
>>> C = template. Context ({'name': 'filena '})
>>>
PrintT. render (c) >>> My name is Adrian. You can also use dict indexes in the template code, and then input the required dict in the context >>>
FromDjango. template
ImportTemplate, Context
>>> Person = {'name': 'Sally ', 'age': '43 '}
>>> T = Template ('{person. name} is {person. age} years old .')
>>> C = Context ({'person ': person })
>>> T. render (c)
U'sally is 43 years old. 'can also use functions, but only functions without parameters can be used >>>
FromDjango. template
ImportTemplate, Context
>>> T = Template ('{var }}-- {var. upper }}-- {var. isdigit }}')
>>> T. render (Context ({'var': 'hello '}))
U'hello -- hello -- false' can also use list indexes, but item. -1 is not allowed> from django. template import Template, Context >>> t = Template ('item 2 is {items.2 }}. ') >>> c = Context ({'items': ['append', 'banas', 'carrots']}) >>> t. render (c) u'item 2 is carrots. 'The above usage is called the Dot Lookup method. When using the dot lookup function to access functions, you must note the following: 1. when a function executed in the template code throws an exception, it will always spread to the upper layer, unless there is a parameter silent_variable_failure = True; in this case, the function information in this error will be rendered as an empty string. >>>
ClassSilentAssertionError (
AssertionError):
... Silent_variable_failure =
True
>>>
ClassPersonClass4:
...
DefFirst_name (
Self):
...
RaiseSilentAssertionError
>>> P = PersonClass4 ()
>>> T. render (Context ({"person": p }))
U'my name is. '2. obviously, calling a function will produce some bad results, such as security vulnerabilities. If you have a BankAccout, write it as {account. delete}. In this way, your account is deleted during rendering .... Therefore, you need to modify your delete function def delete (self): # Delete the accountdelete. alters_data = True # There is no problem with indentation. You can regard delete as an object and set its alters_data attribute. In this way, the rendering will become failed silent. When the simple key value is not found during rendering, it will be failed silent and become an empty string instead of an error reported by the Big Brother. >>> From django. template import Template, Context >>> t = Template ('your name is {name }}. ') >>> t. render (Context () u'your name is. '>>> t. render (Context ({'var': 'hello'}) u 'your name is. 'Context object can also be used to add, delete, and modify values. >>> From django. template import Context >>> c = Context ({"foo": "bar"}) >>> c ['foo'] 'bar' >>> c ['newvariable'] = 'hello' >>> del c ['foo'] >>> c ['foo'] Use python manage. the difference between running the python interactive command line window in py shell and directly starting the interactive command line window in python is that the former will tell Django to import settings by finding a DJANGO_SETTINGS_MODULE environment variable. py configuration information. Basic tag and filter usage tag:
You can use and, or, not to organize your logic. But it is not allowed in the condition statements that both and or appear. There is no such use as {% elif %}. You can use nesting to implement multiple if statements. {% If athlete_list %} <p> Here are the athletes :{{ athlete_list }}. </p >{% else %} <p> No athletes are available. </p >{% if not coach_list %} <p> Here are the coaches :{{ coach_list }}. </p> {% endif %}
It is used to loop through a list. You can also use the resersed keyword for reverse traversal. Generally, you can use the if statement to determine whether the list is empty before traversing; you can also use the empty keyword to redirect when the behavior is empty. {% For athlete in athlete_list resersed %} <li >{{ athlete. name }}</li >{% empty %} <p> There are no athletes. only computer programmers. </p> {% endfor %} for tag also provides some built-in parameters to provide information about template loops. 1. forloop. counter current cycle count, starting from 1: {% for item in todo_list %} <p >{{ forloop. counter }}:{ {item }}</p> {% endfor %} 2. forloop. counter0: Current cyclic count, starting from 0. Standard Index Mode 3. forloop. the reciprocal count of the current loop of revcounter, starting from the list length. forloop. revcounter0 indicates the reciprocal count of the current loop, starting from 1 minus the list length, Standard 5. forloop. first bool value, judge whether it is the first element of the loop 6. forloop. last is the same as above. judge whether it is the last element of the loop. forloop. parentloop is used in a nested loop to get reference of the parent loop. Then, you can use the preceding parameter {% for country in countries %} <table >{% for city in country. city_list %} <tr> <td> Country # {forloop. parentloop. counter }}</td> <td> City # {forloop. counter }}</td> <td >{{ city }}</td> </tr >{% endfor %}</table >{% endfor %}
- Ifequal and ifnotequal. At first glance, we can directly compare the values of tags. Two parameters are required and the usage is limited,
- Only the comparison of strings, integers, decimal places, lists, dictionaries, and tuples is not supported.
{% Ifequal user currentuser %}
{##}: The comment usage in the template, which can only be used in one row
To use multiline comments, use {% comment %} {# This is a comment #}{% comment %} This is amulti-line comment. {% endcomment %} filter: filter is used for some simple processing of variables before they are displayed. You can also perform the chain operation {name | lower }}{ my_list | first | upper }{{ bio | truncatewords using the pipeline-like operator "|: "30"} describes several important filters:
- Addslashes: adds a backslash to any backslash, single quotation marks, and double quotation marks. It is useful when the text contains javascript strings.
- Date: used to format the string information of data and datatime objects.
- {Pub_date | date: "F j, Y "}}
- Length: the length of the returned variable.
Use template in view: first configure the path of the template file in settings. py. TEMPLATE_DIRS = ('/home/django/mysite/templates') Use commas to remember a path, in this way, you can identify whether a tuple or a block expression can also use the python file path operation code: import OS. path TEMPLATE_DIRS = (OS. path. join (OS. path. dirname (_ file _), 'templates '). replace ('\', '/'),) then, you can use the template in the view
FromDjango. template. loader
ImportGet_template
FromDjango. template
ImportContext
FromDjango. http
ImportHttpResponse
ImportDatetime
DefCurrent_datetime (request ):
Now = datetime. datetime. now ()
T = get_template('current_datetime.html ')
Html = t. render (Context ({'current _ date': now }))
ReturnHttpResponse (html) In most cases, you will use a sort cut method, render_to_response () to complete the above work.FromDjango. shortcutsImportRender_to_response
ImportDatetime
DefCurrent_datetime (request ):
Now = datetime. datetime. now ()
ReturnRender_to_response('current_datetime.html ', {'current _ date': now}) locals () tips if you have many variables to pass to render, It is very troublesome to construct dict elements one by one. Directly change the variable name to the variable name required in the template, and then use the locasl () function, which is easy to solve.DefCurrent_datetime (request ):
Current_date = datetime. datetime. now ()
ReturnRender_to_response('current_datetime.html ', locals () will return the dict of the variable information in the local space, which can be directly transmitted to render. However, note that it will return the information of some local variables, some may not be used, such as the request variable. {% Include %} {% include 'nav.html '%} is used to introduce the content of other templates and reduce repeated template code {% include template_name % }, you can also use the variable name. If the include template file is not found, when DEBUG is true, the TemplateDoesNotExist error is reported. When DEBUG is false, the page is blank. It is true that include can effectively reduce repeated template code. However, a more elegant method is: template inheritance.first, create base.html <! Doctype html public "-// W3C // dtd html 4.01 // EN">