标签:render loader turn item you hello create -- templates
django 是python写的,因此里面自然可以用到python的类。下面一个例子,结合jinja2语法。
views.py
from django.shortcuts import render,HttpResponse,render_to_response
from django.template import loader,Context
# Create your views here.
class Person(object):
def __init__(self):
self.name=‘carl‘
self.age=15
self.mail=‘carlw@synnex.com‘
def get_content(self):
return self.name+self.mail
def mainmenu(req):
# t=loader.get_template("index.html")
# c=Context({})
# return render(req,‘index.html‘,locals())
# return HttpResponse(t.render({}))
# return render_to_response("index.html",{})
#user={‘name‘:‘zhoujielun‘,‘age‘:18,‘mail‘:‘zoujielun@sina.com‘}
p=Person()
user=p
#user=[‘小明‘,‘xiaohong‘,‘xiaolan‘]
return render(req,"index.html",locals())
index.html
<h1>hello,
{% if user.name %}
<h1> {{user.name|length}}</h1> <!-- user.get_content -->
{%else%}
{{user.age}}
{%endif%}
</h1>
其中传递给模板的变量可以是字典,对象,和列表等。优先级
字典 > 对象属性 > 对象方法 > 列表
if 模板常用的东西:
{% if condition %}
some html code here
{%else%}
other html code here
{%endif%}
for模板常用东西:
<ul>
{%for item in name%}
<li>
{{ forloop.counter }} #循环次数。从1开始
{%if forloop.first%} #是不是变量中的首个
<h1>first</h1>
{%endif%}
{%if forloop.last%} #是不是来变量的最后一个
<h1>last</h1>
{%endif%}
{{item}}
</li>
{%endfor%}
</ul>
标签:render loader turn item you hello create -- templates
原文地址:https://www.cnblogs.com/mingxiazhichan/p/9011603.html