Django中template 使用

本文详细介绍了在Django中如何使用template,包括在交互模式下使用template的方法,创建和渲染template,Context变量的查阅,方法查阅,以及Context对象的访问。同时,文章还讲解了template中的基本Tag,如条件判断、for语句、ifequal/ifnotequal以及注释的使用,并展示了过滤器filter的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.template 使用
template不仅可以用来导出HTML,他可以用来做任何的
基于文本的处理
1.在交互模式下使用template
	使用django的template时,他需要查找一个变量的
	设置,叫:DJANGO_SETTINGS_MODULE,这个指向的是
	当前的工作项目的settings.py文件,所以,要想在
	交互模式下使用template,最好先通过
	django-admin.py startproject mysite开启一个项目
	然后进入mysite,运行python manage.py shell进入
	交互模式,这样就自动的读取了DJANGO_SETTINGS_MODULE
	变量所指定的配置文件
	当然,你也可以直接运行python,然后只用内置函数再
	设置该变量也可以
2.创建一个template
	from django.template import Context, Template
	t = Template('My name is {{ name }}')
	c = Context({'name':'zhang'})
	t.render(c)
	
	注:Template()构造出一个template对象,她接收一个
		原生template字符串,Context()函数接收一个字典,
		这个用于template对象的render()函数来渲染原生字符串
		注意:t.render()函数返回的是unicode字符串不是
		常用的字符串
	一个例子:
		# 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}))
3.Context变量的查阅
	>>> 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.'
	这里使用字典来渲染template,可以使用点好"."来访问
	其对象中包含的属性,非常简洁
	同样的使用,可以用来访问对象的方法,属性,但访问
	对象的方法时不能有括号,所以不能调用需要参数的方法
	如:string的isdigit(),upper()这些方法可以的
	>>> from django.template import Template, Context
	>>> t = Template('{{ var }} -- {{ var.upper }} -- {{ var.isdigit }}')
	>>> t.render(Context({'var': 'hello'}))
	u'hello -- HELLO -- False'
	>>> t.render(Context({'var': '123'}))
	u'123 -- 123 -- True'
	
	点查阅总结:
		当template对象遇到点号时,按如下顺序进行查阅:
			1.字典查阅	eg: foo['bar']
			2.属性查阅	eg: foo.bar
			3.方法查阅	eg: foo.bar()
			4.list索引查阅	eg: foo[0] 没有证实成功
	
	方法查阅:
		1.如果方法在执行过程中有异常产生,如果在方法中有
		一个变量silent_variable_failure设置为true,则该异常
		不会输出,template会以空字符替代,如:
		>>> t = Template("My name is {{ person.first_name }}.")
		>>> class PersonClass3:
		...     def first_name(self):
		...         raise AssertionError, "foo"
		>>> p = PersonClass3()
		>>> t.render(Context({"person": p}))
		Traceback (most recent call last):
		...
		AssertionError: foo


		>>> class SilentAssertionError(AssertionError):
		...     silent_variable_failure = True
		>>> class PersonClass4:
		...     def first_name(self):
		...         raise SilentAssertionError
		>>> p = PersonClass4()
		>>> t.render(Context({"person": p}))
		u'My name is .'
4.Context对象访问
	当初始化Context为字典时,可以像字典一样访问context中的属性,赋值
	from django.template import Context, Template
	c = Context({'foo':'bar})
	c['foo']	->  'bar' 访问属性


	del c['foo'] ->删除foo


	c['foo']	->出错


	c['hello'] = 'hello world'	->赋值


5.Template中的基本的Tag
1.普通的条件判断: {% if %} {% else %} {% elseif %} {% endif %}
	补充:
		python中被认为为False的
		1.空list	[]
		2.空tuple	()
		3.空字典	{}
		4.空字符串	''
		5.零		0
		6.特殊对象	None
		7.			False
		8.定制的对象,自己定制了Boolean的行为,这个在Python的高级中使用
		9.其他的所有都是True
2.for语句	
	{% for item in todo_list %}
		<p>{{ forloop.counter }}: {{ item }}</p>
	{% endfor %}
	注:for中,
		forloop.counter		在迭代过程中从1递增到list的长度
		forloop.counter0	在是0索引的序列中是以0递增的list的长度减一
		forloop.revcounter	在迭代过程中从list长度递减到1
		forloop.revcounter	在以0索引为开否的对象中,以长度减一开始递减至0
		forloop.first		当是第一次访问时,被设置为True,这个对于一些输出
							控制很有好处
		forloop.last		当是最后一次访问时,被设置为True
		forloop.parentloop.counter	父级的循环计数器
3.ifequal/ifnotequal
	{% ifequal user currentuser %}
	    <h1>Welcome!</h1>
	{% endifequal %}
4.注释
	{# This is a comment #}
5.过滤器filter
	{{ name|lower }}
	过滤器的原理是管道pipe,即第一个命令的输出是第二个命令的输入,这里将name的输出
	转换为小写
	{{ my_list|first|upper }}
	这里将my_list的第一个元素转换为大写输出
	{{ pub_date|date:"F j, Y" }}
	这里将put_date的输出给date,date通过格式化后输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值