模板的使用:
from django.conf import settings
settings.configure()
from django.template import Template, Context
t = Template(‘hello,{{name}}’)
c = Context({‘name’:’San’})#里面是字典类型
t.render(c)
p = {‘name’:’San’,’age’:’23’}
t = Template(‘{{person.name}} is {{person.age}} years old.’)
c = Context({‘person’:p})
t.render(c)
from django.template import Template, Context
import datetime
d = datetime.date(1993, 6, 7)
t = Template(‘The month is {{ date.month }} and the year is {{ date.year }}.’)
c = Context({‘date’: d})
t.render(c)
[out]:u’The month is 6 and the year is 1993.’
from django.template import Template, Context
t = Template(‘{{ var }} – {{ var.upper }} – {{ var.isdigit }}’)
t.render(Context({‘var’: ‘hello’}))
[out]:u’hello – HELLO – False’
from django.template import Template, Context
t = Template(‘Item 2 is {{ items.2 }}.’)
c = Context({‘items’: [‘apples’, ‘bananas’, ‘carrots’]})
t.render(c)
[out]:u’Item 2 is carrots.’
from django.template import Template, Context
person = {‘name’: ‘Sally’, ‘age’: ‘43’}
t = Template(‘{{ person.name.upper }} is {{ person.age }} years old.’)
c = Context({‘person’: person})
t.render(c)
[out]:u’SALLY is 43 years old.’
c = Context({“foo”: “bar”}也可以像python中的字典那样进行操作,使用del c[foo]来删除,使用c[‘newvariable’] = ‘hello’来进行赋值或者覆盖
{%for%}
…
{%endfor%}
循环中有forloop变量。forloop.first,forloop.last是布尔值,forloop.counter和forloop.counter0分别从1和0开始计数
在django中不允许执行python语句。如果要进行两个变量之间的比较使用ifequal和ifnotequal
{% ifequal user correntuser %}
……
{% endifequal %}
只有模板变量,字符串,整数和小数可以作为{%ifequal%}标签的参数 。
{% ifequal variable 1 %}
{% ifequal variable 1.23 %}
{% ifequal variable ‘foo’ %}
{% ifequal variable “foo” %}
而字典,布尔,列表不能使用在{% ifequal %}标签中。
注释使用{#……#}
也可以使用
{% comment %}
……
……
{% endcomment %}
来进行多行注释。
过滤器
{{ name|lower }}小写
{{ my_list|first|upper }}列表的第一个元素并将其转化为大写
{{ bio|truncatewords:”30” }}将显示变量 bio 的前30个词
Tips:
路径最好使用“/”而不是“\”,不论在win下还是linux下。
设置setting中的template路径:
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), ‘templates’).replace(‘\\’,’/’),
)
from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response(‘current_datetime.html’, {‘current_date’: now})
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response(‘current_datetime.html’, locals())
#locals() 囊括了函数执行到该时间点时所定义的一切变量。
#但是变量名要和html中定义的变量名一致
模板的继承。
base.html中定义各种可以被子模板中的相应块填充的框架。
需要继base.html时,需要在开头写上{% extends “base.html”%},就行了。在使用中只要替换相应的block就行了。