1.DTL模板变量使用语法
模板中可以包含变量,Django在渲染模板的时候,可以传递变量对应的值过去进行替换。变量的命名规范和Python非常类似,只能是阿拉伯数字和英文字符以及下划线的组合,不能出现标点符号等特殊字符。变量需要通过视图函数渲染,视图函数在使用render或者render_to_string的时候可以传递一个context的参数,这个参数是一个字典类型。模板中接收变量的时候 使用 {
{ 变量名 }} 这样去接收。
示例代码:
# views.py代码
def profile(request):
return render(request,'profile.html',context={'username':'juran'})
class Person(object):
def __init__(self,username):
self.username = username
def index(request):
p = Person("居然")
content = {
'person':p
}
content = {
'persons':[
'a',
'b',
'c'
]
}
return render(request,"index.html",context=content)
# profile.html模板代码
<h1>{
{ username }}</h2>
<h2>{
{person.username}}</h2>