zoukankan      html  css  js  c++  java
  • django模板

    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>
    

      

  • 相关阅读:
    开通第一天,以此随笔作为纪念
    Apache 基于IP访问网站
    命令解释
    vi总结
    RAID
    Windows虚拟机安装
    CentOS虚拟机安装
    通过挂载系统光盘搭建本地yum仓库的方法
    VMware workstation 的安装
    Linux下关于vi命令的详细解说
  • 原文地址:https://www.cnblogs.com/mingxiazhichan/p/9011603.html
Copyright © 2011-2022 走看看