The Definitive Guide To Django 2 学习笔记(六) 第四章 模板 (二)使用模板系统

模板系统不是django特有的,它是python的一个库,你可以在任何地方使用它。

 

使用方法:

1.使用 Template()方法创建Template对象。2.调用Template对象的render()方法。

>>> 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.

 

创建Template对象


在mysite项目中,输入python manage.py shell 启动交互解释器。

>>> from django.template import Template
>>> t = Template('My name is {{ name }}.')
>>> print t

输出:

<django.template.Template object at 0xb7d5f24c>

0xb7d5f24c 每次都不一样,它是python内部的识别标识。

 

如果代码有错,会出现错误提示。

>>> from django.template import Template
>>> t = Template('{% notatag %}')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
...
django.template.TemplateSyntaxError: Invalid block tag: 'notatag'

block tag这里指代 {%notatag%}.

系统触发了TemplateSyntaxError异常 因为以下情形:

1.无效的tages

2.无效的参数

3.无效的过滤器

4.无效的template syntax

5.未闭合的tags

 

展示模板

创建完模板后,接下来就可以给模板一个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.'

需要指出的是这里的字符串是Unicode,这可以从字符串的前缀u看出来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值