Basics
A template is a text document or a normal Python string, which is marked-up using the Django template language.
A template can contain block tags or variables.
A block tag is a symbol within a template that does something.
For example, a block tag can output content, serve as a control structure (as ' if ' statement or ' for ' loop), grab content From a database or enable access to other template tags.
such as:
{% if is_logged_in%} Thanks for logging in! {% Else%} Please log in.{% endif%}
Block tags is surrounded by '{%' and '%}'.
A varible is a symbol within a template, that outputs a value.
Variable tags is surrounded by '{{' and '}}'.
such as:
My First Name is {{first_name}}. My Last name is {{last_name}}.
Use the template system
It is a two-step process for using the template system in Python.
- First, you compile the raw template code into a template object.
- Second, the The render () method of the Template object with a given context.
>>> fromDjango.templateImportTemplate, Context#Create a Template object>>> t = Template ("My name is {{my_name}}.") >>>PrintT<django.template.base.template Object at 0x00000000034a8a58>#Create a Context object>>> C = Context ({"My_name":"Elen"}) #render the created Template object>>>T.render (c) U'my name is Elen.'
Note:
The constructor of the Context class takes the optional arguments:
- A Dictionary mapping variable names to variable values.
- The name of the current application. This application name was used help resolve namespaced urls.if You do not need and you can ignore this argument.
Variables and Lookups:
Variable names must consist of any letter, any digit, an underscore (not start) or a dot.
Dots has a special meaning in template rendering. A dot in varible name signifies a lookup. When the template system encounters a dot-a variable name, it tries the following lookups (in this order): Dictionar Y, Attribute, Method call, List-index.
>>> fromDjango.templateImportContext, Template>>> t = Template ("My name is {{person.first_name}}.")>>> d = {" Person": {"first_name":"Joe","last_name":"Johnson"}}>>>T.render (Context (d))"My name is Joe.">>>classPersonclass:Pass>>> p =Personclass ()>>> P.first_name ="Ron">>> P.last_name ="Nasty">>> T.render (Context ({" Person": P}))"My name is Ron.">>> t = Template ("The first stooge in the list is {{stooges.0}}.")>>> C = Context ({"Stooges": ["Larry","Curly","Moe"]})>>>T.render (c)>>>classPersonClass2: ...defname (self): ...return "Samantha">>> t = Template ("My name is {{person.name}}.")>>> T.render (Context ({" Person": PersonClass2}))"My name is Samantha."
Playing with Context objects
Most of the time, you'll instantiate Context objects by passing in a fully-populated dictionary to Context () /c1>. But you can add and delete items from a Context object Once it's been instantiated, too, using standard Dictionar Y syntax:
>>> fromDjango.templateImportContext>>> C = Context ({"Foo":"Bar"})>>> c['Foo']'Bar'>>>delc['Foo']>>> c['Foo']"'>>> c['newvariable'] ='Hello'>>> c['newvariable']'Hello'
Context.pop () Context.push () context.update (other_dict)
A Context object is a stack. That's, you can push () and pop () it. The update () method works like push () but takes a dictionary as an argument an pushes that dictionary onto the stack inste Ad of an empty one.
subclassing Context:requestcontext:
1) The Django.template.RequestContext takes an HttpRequest as its first argument.
such as:
c = RequestContext (request, { 'foo'bar ') ,})
2) The Django.template.RequestContext automatically populates the context with a few cariables, according to your Templ Ate_context_processors setting.
The template_context_processors setting is a tuple of callables–called CONTEXT processors –that take A request object as their argument and return a dictionary of items to being merged into the context.
Also, you can give requestcontext a list of additional processors, using the optional, third positional argument, processors. In this example, the RequestContext instance gets a IP_Address variable:
fromDjango.httpImportHttpResponse fromDjango.templateImportRequestContextdefip_address_processor (Request):return{'IP_Address': Request. meta['REMOTE_ADDR']}defSome_view (Request):# ...c =RequestContext (Request, {'Foo':'Bar',}, [Ip_address_processor])returnHttpResponse (T.render (c))
Loading templates
Django searches fot template directories in a number of place, depending on your template-loader settings, but the most BA Sic specifying template directories is by using the Template_dirs setting.
Your templates can go anywhere you want, as long as the directories and templates is readable by the WEB server.
Note that these paths should use unix-style forward slashes, even on Windows.
Templates
A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.).
A template contains variables, which get replaced with values while the template is evaluated, and tags, which control the Logic of the template.
Below is a minimal template, that illustrates a few basic.
{% extends "base_generic.html"%}{% block title%}{{section.title}}{% endblock%}{% block content%}<H1>{{Section.title}}</H1>{% for stories in story_list%}<H2> <ahref= "{{Story.get_absolute_url}}">{{Story.headline|upper}}</a></H2><P>{{story.tease|truncatewords: ' 100 '}}</P>{% endfor%}{% endblock%}
In the above example:
Variables
{{Section.title}} is replaced with the title attribute of the section object.
If you use a varible that doesn ' t exist, the template system would insert the value of the Template_string_if_invalid Setti Ng, which is set to "(The empty string) by default.
Filters
You can modify variables for display by using filters.
{{Name|lower}} Convert the value of {{name}} to lowercase by using a pipe ' | ' to apply a filter.
Filters can be chained. The output of one filter is applied to the next.
{{Text|escape|linebreaks}} is a common idiom for escaping text contents, then converting line breaks to <P&G T Tags.
Some filters take arguments. {{bio|truncatewords:30}} would display the first words of the bio variable.
Django provides about thirty built-in template filters. You can read all in the bulit-in filter reference.
Tags
Tags look like this:{% tag%}.
Some tags require beginning and ending tags (i.e. {% tag%}...tag contents ... {% Endtag%}).
Django ships with about the dozen built-in template tags. You can read all in the built-in tag reference.
You can also create your own custom template tags, see costom template tags and filters.
Comment
Ignores everything between {% comment%} and {% endcomment%}. An optional note is inserted in the first tag.
< P > Rendered text with {{pub_date|date: "C"}}</p>{% comment "Optional note"%}
<p>commented out text with {{create_date|date: "C"}}</p >{% endcomment%}
Comment tags cannot be nested.
Comments
To comment-out part of a line in a template, use the comment syntax:{# #}.
This syntax can is used for single-line comments. No newlines is permitted between the {# and #} delimiters.
Template inheritance
The most powerful–and thus the most complex–part of the Django's template engine is template inheritance. Template inheritance allows you to build a base "skeleton" template, contains all the common elements of your site and Defines blocks that child templates can override.
such as in a child template:
{% extends "base.html"%}
The extends tag is key. It tells the template engine that this template ' extends ' another template. When the template system is evaluates this template, first it locates the parent-in this case, 'base.html'.
A block tag does is to tell the template engine, a child template may override those portions of the template .
If 'base.html' has the block tags, the template engine would notice that and replace those blocks with the content s of the child template. If child template didn ' t define someone block, the value from the parent template is uesd instead. Content within a {% block%} tag in a parent template was always used as a fallback.
Here is some tips for working with inheritance:
- {% extends%} must is the first template tag in that template.
- More {% block%} tags in your base templates is better. Remember, child templates don ' t has to define all the parent blocks, so can fill in reasonable defaults in a number of BL Ocks define the ones you need later. It ' s better to has more hooks than fewer hooks.
- If you need to get the content of the block from the parent template, the {{block.super}} variable would do the Trick.
Django Template language