您现在的位置:首页 >> 前端 >> 内容

djangotemplate基础,上下文对象

时间:2017/7/24 9:27:48 点击:

  核心提示:django template 基础(模板对象(Template),上下文对象(Context))1 启动python环境: python manage.py shell从项目目录下,通过 pytho...

django template 基础(模板对象(Template),上下文对象(Context))

1 启动python环境: python manage.py shell

从项目目录下,通过 python manage.py shell 来启动 :与直接使用python 命令的不同是,会告诉django 的使用的配置文件 settings

2 创建Template,Context对象:

创建对象代码

from django.template import Context, Template
t = Template("select {{id}}, {{name}} from {{table}}")
d ={'name':'name' , 'id':'id' , 'table':'table'}
c = Context(d)
t.render(c)

注意:t.render(c)返回的值是一个Unicode对象,一个模板可以被多个context对象渲染控制

3 Context 上下文

1 if/else选择

from django.template import Context, Template
template = '''
    select t.id,
           t.name,
           {% if count %}
           count(t.age)
           {% else %}
           sum(t.age)
           {% endif %}
      from {{table}}     
    group by t.id,t.name
'''
t2 = Template(template)
print(t2.render(c))

输出结果:

  select t.id,
          t.name,

          sum(t.age)

     from table
   group by t.id,t.name

总结:

基本用法 {% if 变量 %} : 当变量 为flast或者不存在的时候,渲染else(可选)部分,{% endif %}语句结束

2. for 循环

class Student():
    def __init__(self,name,age):
        self.id = name
        self.age = age

stlist = []        
for i in range(5):
    st = Student('inx'+str(i),i+20)
    stlist.append(st)

template2 = '''
{% if stlist %}
    students:
    {% for st in stlist %}
    {% if forloop.first %} student {{forloop.counter}}:{{st.name}},{{st.age}} the bigbrather {% endif %}
    student {{forloop.counter}}:{{st.name}},{{st.age}}
    {% empty %}
    no students
    {% endfor %}
{% else %}
    no student!!!
{% endif %}
'''
t3 = Template(template2)
str = t3.render(Context({'stlist':stlist}))
print(str)

打印结果(忽略换行):
students:
student 1:,20 the bigbrather
student 1:,20
student 2:,21
student 3:,22
student 4:,23
student 5:,24
总结:

1 基本用法 :{% for st in stlist %} ……{%endfor%} 2 forloop模块变量: counter: 循环的计数器 从1开始 counter0: 循环的计数器 从0开始 revcounter: 反向计数器,以1结束 revcounter0: 反向计数器,以0结束 first: 布尔值,第一次循环的时候为TRUE last: 布尔值,最后一次循环的时候为TRUE parentloop:上次forloop对象的引用 3{% empty %} 列表为空时执行 4 {% for %} 中还能 嵌套 {% for %}

3. 过滤器

{{ name|lower }} : 将name的值全部改成小写 {{ my_list|first|upper }} #嵌套过滤,将myfist 首字母小写 {{ bio|truncatewords:”30” }} #截取前30个字符 {{ pub_date|date:”F j, Y” }} #格式化pub_date时间字符串

4 ifequal/ifnoequal : 判断两个变量值是否相等

示例:

{% ifequal user currentuser %}Welcome!{% endifequal %} :判断user 与currentuser是否相等

{% ifequal section “community” %}Community{% else %}Site News{% endifequal %}

注意: ifequal/ifnoequal 只能比较模板变量,字符串,小数,整数,不能用字典类型、列表类型、布尔类型,直接比较 如:不支持{% ifequal variable True %}

5 注释:

单行注释:
{# This is a comment #} ; 多行注释:
{% comment %}
This is a
multi-line comment.
{% endcomment %}

Tags:DJ JA AN NG 
作者:网络 来源:大鹰的天空