3.5.template语法及过滤器
完整模板语法请见 模板
完整过滤器请见 Built-in template tags and filters
模板语法示例
条件语句
if
{% if my_message.name == 'bobby' %}bobby_test{% endif %}
if ... else ...
{% if not my_message.name == 'bobby' %}has_bobby{% else %}no_has_bobby{% endif %}
ifequal
{% ifequal my_message.name 'sophie' %}has_bobby{% else %}no_has_bobby{% endifequal %}
循环语句
for
{% for hot_org in hot_orgs %}
{{ forloop.counter }} // 获取循环的index
{{ hot_org.name }}
{% endfor %}
过滤器
整型转字符串
city.id|stringformat:'i'
字符截取
{% ifequal my_message.name|slice:'5' 'sophie' %}has_bobby{% else %}no_has_bobby{% endifequal %}
为空时显示默认值
{{ request.user.mobile|default_if_none: '' }}
示例
<input id="name" type="text" name="name" class="error"
value="{% ifequal my_message.name|slice:'5' 'sophie' %}has_bobby{% else %}no_has_bobby{% endifequal %}"
placeholder="请输入您的姓名"/>
urls配置技巧
配置别名
hello_django/urls.py
urlpatterns = [
path('form/', form_view, name='go_form'),
...
]
使用{% url '...' %}代替硬编码
templates/message.html
<form action="{% url 'go_form' %}" method="post" class="smart-green">
...
</form>
Last updated
Was this helpful?