标签:数据类型 http 应用程序 header pre 执行 ril text john
转载自:http://www.aichengxu.com/python/60625.htm
一旦你创建一个 Template 对象,你可以用 context 来传递数据给它。 一个context是一系列变量和它们值的集合。
context在Django里表现为 Context 类,在 django.template 模块里。 她的构造函数带有一个可选的参数: 一个字典映射变量和它们的值。 调用 Template 对象 的 render() 方法并传递context来填充模板:>>> from django.template import Context, Template >>> t = Template(‘My name is {{ name }}.‘) >>> c = Context({‘name‘: ‘Stephane‘}) >>> t.render(c) u‘My name is Stephane.‘
>>> from django.template import Template, Context >>> raw_template = """<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> ... ... {% 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>""" >>> t = Template(raw_template) >>> import datetime >>> c = Context({‘person_name‘: ‘John Smith‘, ... ‘company‘: ‘Outdoor Equipment‘, ... ‘ship_date‘: datetime.date(2009, 4, 2), ... ‘ordered_warranty‘: False}) >>> t.render(c) u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from Outdoor Equipment. It‘s scheduled to\nship on April 2, 2009.</p>\n\n\n<p>You didn‘t order a warranty, so you‘re on your own when\nthe products inevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment </p>"
>>> from django.template import Template, Context >>> t = Template(‘Hello, {{ name }}‘) >>> print t.render(Context({‘name‘: ‘John‘})) Hello, John >>> print t.render(Context({‘name‘: ‘Julie‘})) Hello, Julie >>> print t.render(Context({‘name‘: ‘Pat‘})) Hello, Pat
# Bad for name in (‘John‘, ‘Julie‘, ‘Pat‘): t = Template(‘Hello, {{ name }}‘) print t.render(Context({‘name‘: name})) # Good t = Template(‘Hello, {{ name }}‘) for name in (‘John‘, ‘Julie‘, ‘Pat‘): print t.render(Context({‘name‘: name}))
标签:数据类型 http 应用程序 header pre 执行 ril text john
原文地址:https://www.cnblogs.com/zpaixx/p/10566777.html