标签:
1.一个简单的模板例子:
<html> <head><title>Ordering notice</title></head> <body> <h1>Ordering notice</h1> <p>Dear {{ person_name }},</p> <p>Thanks for placing an order from {{ company }}. It‘s scheduled to ship on {{ ship_date|date:"F j, Y" }}.</p> <p>Here are the items you‘ve ordered:</p> <ul> {% for item in item_list %} <li>{{ item }}</li> {% endfor %} </ul> {% if ordered_warranty %} <p>Your warranty information will be included in the packaging.</p> {% else %} <p>You didn‘t order a warranty, so you‘re on your own when the products inevitably stop working.</p> {% endif %} <p>Sincerely,<br />{{ company }}</p> </body> </html>
2.模板系统工作原理
在Python代码中使用Django模板的最基本方式如下:
1. 可以用原始的模板代码字符串创建一个 Template 对象, Django同样支持用指定模板文件路径的方式来创建 Template 对象;
2. 调用模板对象的render方法,并且传入一套变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换;
>>> from django import template >>> t = template.Template(‘My name is {{ name }}.‘) >>> c = template.Context({‘name‘: ‘Adrian‘}) >>> print t.render(c) My name is Adrian. >>> c = template.Context({‘name‘: ‘Fred‘}) >>> print t.render(c) My name is Fred.
系统会在下面的情形抛出 TemplateSyntaxError 异常:
3.模板的渲染
>>> from django.template import Context, Template >>> t = Template(‘My name is {{ name }}.‘) >>> c = Context({‘name‘: ‘Stephane‘}) >>> t.render(c) u‘My name is Stephane.‘
t.render(c) 返回的值是一个 Unicode 对象,不是普通的 Python 字符串。 你可以通过字符串前的 u 来区分。 在框架中,Django 会一直使用 Unicode 对象而不是普通的字符串。
在 Django 模板中遍历复杂数据结构的关键是句点字符 (.)。
最好是用几个例子来说明一下。 比如,假设你要向模板传递一个 Python 字典。 要通过字典键访问该字典的值,可使用一个句点:
>>> from django.template import Template, 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.‘
--------------------------------------------------
4.用render_to_response()简化views层
简化操作,不同加载模板那个过程render_to_response() 的第一个参数必须是要使用的模板名称。 如果要给定第二个参数,那么该参数必须是为该模板创建 Context 时所使用的字典。 如果不提供第二个参数, render_to_response() 使用一个空字典。
标签:
原文地址:http://www.cnblogs.com/zzblee/p/4725004.html