模版2-django
模版2-django
@(python)
if else、ifequal/ifnotequal
- if/else
{% if %}标签计算一个变量值,如果是“true”,即它存在、不为空并且不是false的boolean值,系统则会显示{% if %}和{% endif %}间的所有内容:
{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% else %}
<p>Get back to work.</p>
{% endif %}
{% if %}标签接受and,or或者not来测试多个变量值或者否定一个给定的变量,例如:
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches.
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}
{% if %}标签不允许同一标签里同时出现and和or,否则逻辑容易产生歧义,例如下面的标签是不合法的:
代码
{% if athlete_list and coach_list or cheerleader_list %}
多次使用同一个逻辑符号是合法的:
{% if athlete_list or coach_list or parent_list or teacher_list %}
- ifequal/ifnotequal
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}
参数可以是硬编码的string,单引号和双引号均可,下面的代码是合法的:
{% ifequal section 'sitenews' %}
<h1>Site News</h1>
{% endifequal %}
{% ifequal section "community" %}
<h1>Community</h1>
{% endifequal %}
其它的模板变量,strings,integers和小数都可以作为{% ifequal %}的参数:
{% ifequal variable 1 %}
{% ifequal variable 1.23 %}
{% ifequal variable 'foo' %}
{% ifequal variable "foo" %}
注释
和HTML或编程语言如Python一样,Django模板语言允许注释{# #},如:
{# This is a comment #}
block标签
{% block %}: 所有的 {% block %} 标签告诉模板引擎,子模板可以重载这些部分。 每个{% block %}标签所要做的是告诉模板引擎,该模板下的这一块内容将有可能被子模板覆盖。
- 在模版文件夹新建base.html
<html>
<body>
{% block content %}<p>parent</p>{% endblock %}
</body>
</html>
- 新建block.html继承base.html
{% extends "base.html" %}
{% block content %}child{% endblock %}
- 添加一下代码views.py
def show_block(request):
return render_to_response('block.html')
- 添加url规则
url('^show_block/$', 'users.views.show_block'),
- 打开浏览器http://ip/show_block/会输出
child
参考文献
http://www.cnblogs.com/mfryf/archive/2012/07/17/2595019.html