Django模板用法

django模板原理

# 创建template对象,由context对象传递template所需要的值, 有render方法进行模板的呈现

# 写模板,创建 Template 对象,创建 Context , 调用 render() 方法。

# Python 字符串都有 upper() 和 isdigit() 方法,你在模板中调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# 执行变量
{{ abc }}
 
# 判断
{% if x > 0 %}
{% else %}
{% endif %}
 
例:
{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% endif %}
注意: 模板中不能包括 ()
{% if athlete_list or coach_list %}
    There are some athletes or some coaches.
{% endif %}
 
# 循环
{% for in items_list %}
 
例:
{% for athlete in athlete_list reversed %}
    <li>{{ athlete.name }}</li>
{% empty %}
    <p>There are no athletes. Only computer programmers.</p>
{% endfor %}
 
# forloop的一个用法
# forloop循环的结构控制语法
{% for link in links %}{{ link }}{% if not forloop.last %} | {% endif %}{% endfor %}
 
# forloop实现结构控制的变量   forloop.parentloop.counter 父计数器   
# forloop.counter 当前计数器   接下来可以采用 if 进行逻辑控制
{% 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 section 'sitenews' %}
    <h1>Site News</h1>
{% else %}
    <h1>No News Here</h1>
{% endifequal %}
 
#注释及多行注释
{# This is a comment #}
{% comment %}
This is a
multi-line comment.
{% endcomment %}
 
# 过滤器之后管道给lower  ,,, truncatewords
{{ name | lower }}
{{ pub_date | date:"F j, Y" }}
 
# 模板加载
import os.path
 
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
 
from django.shortcuts import render_to_response
return render_to_response('current_datetime.html', {'current_date': now})
 
# 模板的继承 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>
 
{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}





     本文转自My_King1 51CTO博客,原文链接:http://blog.51cto.com/apprentice/1532424,如需转载请自行联系原作者



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值