标签:
Basics
A template is a text document or a normal Python string, that 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 are surrounded by ‘{%‘ and ‘%}‘.
A varible is a symbol within a template that outputs a value.
Variable tags are 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.
>>> from django.template import Template, Context # create a Template object >>> t = Template("my name is {{ my_name }}.") >>> print t <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 Context class takes two optional arguments:
Variables and lookups:
Variable names must consist of any letter, any digit, an underscore(not start) or a dot.
Dots have a special meaning in template rendering. A dot in varible name signifies a lookup.When the template system encounters a dot in a variable name, it tries the following lookups(in this order): Dictionary, Attribute, Method call, List-index.
>>> from django.template import Context, 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." >>> class PersonClass: 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) >>> class PersonClass2: ... def name(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(). But you can add and delete items from a Context object once it‘s been instantiated, too, using standard dictionary syntax:
>>> from django.template import Context >>> c = Context({"foo": "bar"}) >>> c[‘foo‘] ‘bar‘ >>> del c[‘foo‘] >>> c[‘foo‘] ‘‘ >>> c[‘newvariable‘] = ‘hello‘ >>> c[‘newvariable‘] ‘hello‘
Context.pop() Context.push() Context.update(other_dict)
A Context object is a stack.That is, 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 instead 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 TEMPLATE_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 be 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:
from django.http import HttpResponse from django.template import RequestContext def ip_address_processor(request): return {‘ip_address‘: request.META[‘REMOTE_ADDR‘]} def some_view(request): # ... c = RequestContext(request, { ‘foo‘: ‘bar‘, }, [ip_address_processor]) return HttpResponse(t.render(c))
Loading templates
Django searches fot template directories in a number of place, depending on your template-loader settings, but the most basic way of specifying template directories is by using the TEMPLATE_DIRS setting.
Your templates can go anywhere you want, as long as the directories and templates are 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 when 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 story in story_list %} <h2> <a href="{{ story.get_absolute_url }}"> {{ story.headline|upper }} </a> </h2> <p>{{ story.tease|truncatewords:"100" }}</p> {% endfor %} {% endblock %}
In the above example:
Variables
{{ section.title }} will be replaced with the title attribute of the section object.
If you use a varible that doesn‘t exist, the template system will insert the value of the TEMPLATE_STRING_IF_INVALID setting, 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> tags.
Some filters take arguments.{{ bio|truncatewords:30 }} will display the first 30 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 two dozen built-in template tags.You can read all in the built-in tag reference.
You can also create you own custom template tags, see Costom template tags and filters.
Comment
Ignores everything between {% comment %} and {% endcomment %}. An optional note may be 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 only be used for single-line comments.No newlines are permitted between the {# and #} delimiters.
Template inheritance
The most powerful – and thus the most complex – part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that 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 evaluates this template, first it locates the parent - in this case, ‘base.html‘.
A block tag does is to tell the template engine that a child template may override those portions of the template.
If ‘base.html‘ has the block tags, the template engine will notice that and replace those blocks with the contents 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 is always used as a fallback.
Here are some tips for working with inheritance:
标签:
原文地址:http://www.cnblogs.com/wddoer/p/4350232.html