django模板原理
# 创建template对象,由context对象传递template所需要的值, 有render方法进行模板的呈现
# 写模板,创建 Template 对象,创建 Context , 调用 render() 方法。
# Python 字符串都有 upper() 和 isdigit() 方法,你在模板中调用
# 执行变量
{{ 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 i 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 %}本文出自 “Apprentice” 博客,请务必保留此出处http://apprentice.blog.51cto.com/2214645/1532424
原文:http://apprentice.blog.51cto.com/2214645/1532424