码迷,mamicode.com
首页 > 其他好文 > 详细

django view

时间:2018-05-09 00:00:46      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:render   loader   turn   item   you   hello   create   --   templates   

1,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>

  其中传递给模板的变量可以是字典,对象,和列表等。优先级

   字典 > 对象属性 > 对象方法  > 列表

2.if

if 模板常用的东西:

                {% if condition %}
                 some html code here
                {%else%}
                other html code here
                {%endif%}

3.for

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>

  

django view

标签:render   loader   turn   item   you   hello   create   --   templates   

原文地址:https://www.cnblogs.com/mingxiazhichan/p/9011603.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!