Django Template

动态URL

在urls.py中以通配符来实现

urlpatterns = patterns('',
    (r'^hello/$', hello),
    (r'^time/$', current_datetime),
    (r'^time/plus/(\d{1,2})/$', hours_ahead),
)
def showNumber(request,num):#num是匹配值
    try:
        NUM = int(num)
    except ValueError:
        raise Http404()
    return  HttpResponse('number is %d' %NUM)

context

#coding:utf8
from  django.template import Template,Context
person ={'name':'eric','age':20,'sex':'man'}
c = Context({'person':person})#将字典person转换成Context
t = Template('{{person.name}} age is {{person.age}} he is {{person.sex}}')
print t.render(c)

forloop

  • forloop 属性统计当前循环次数
{% for item in todo_list %}
    <p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}
  • forloop.counter0 类似于 forloop.counter ,但是它是从0计数的。 第一次执行循环时这个变量会被设置为0。

  • forloop.revcounter 是表示循环中剩余项的整型变量。 在循环初次执行时 forloop.revcounter 将被设置为序列中项的总数。 最后一次循环执行中,这个变量将被置1。

  • forloop.revcounter0 类似于 forloop.revcounter ,但它以0做为结束索引。 在第一次执行循环时,该变量会被置为序列的项的个数减1。

  • forloop.first 是一个布尔值,如果该迭代是第一次执行,那么它被置为True
  • forloop.last 是一个布尔值;在最后一次执行循环时被置为True
  • forloop.parentloop 是一个指向当前循环的上一级循环的 forloop 对象的引用(在嵌套循环的情况下)。 例子在此:
{% for country in countries %}
    <table>
    {% for city in country.city_list %}
        <tr>
        <td>Country #{{ forloop.parentloop.counter }}</td>
        <td>City #{{ forloop.counter }}</td>
        <td>{{ city }}</td>
        </tr>
    {% endfor %}
    </table>
{% endfor %}

ifequal

  • 如果相等显示中间代码
{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% endifequal %}

{% ifequal section "community" %}
    <h1>Community</h1>
{% endifequal %}

只有模板变量,字符串,整数和小数可以作为 {% ifequal %} 标签的参数

{% ifequal variable 1 %}
{% ifequal variable 1.23 %}
{% ifequal variable 'foo' %}
{% ifequal variable "foo" %}

多行注释

{% comment %}
This is a
multi-line comment.
{% endcomment %}

过滤器

#将列表的第一个元素大写
{{ my_list|first|upper }}

#显示变量的前30个词
{{ bio|truncatewords:"30" }}

#格式化字符串
{{ pub_date|date:"F j, Y" }}

addslashes : 添加反斜杠到任何反斜杠、单引号或者双引号前面。 这在处理包含JavaScript的文本时是非常有用的。

绝对路径设置

'DIRS': [os.path.join(BASE_DIR, 'templates')],

import os.path
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

# BASE_DIR 、os.path.dirname(__file__)都是获取当前文件路径

载入模板文件,Context渲染

def current_datetime(request):
    now = datetime.datetime.now()
    t = get_template('current_datetime.html')#获取模板文件
    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)

include模板标签

用于减少代码重复

# mypage.html

<html>
<body>
{% include "includes/nav.html" %}
<h1>{{ title }}</h1>
</body>
</html>

# includes/nav.html

<div id="nav">
    You are in: {{ current_section }}
</div>

模板继承

  • base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>
</html>
  • 子模板1
{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}
  • 子模板2
{% extends "base.html" %}

{% block title %}Future time{% endblock %}

{% block content %}
<p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
{% endblock %}
posted @ 2017-10-15 23:42  icanactnow  阅读(99)  评论(0)    收藏  举报