0
点赞
收藏
分享

微信扫一扫

Django中template中html中fro循环和过滤器

肉肉七七 2022-07-12 阅读 66


一、高级操作

1.template中判断行数奇偶

方法一: {{forloop.counter|divisibleby:2}}

方法二:{% cycle 'odd' 'even' %}

2.for和with联合用法

{% for x in some_list %}
{% with y=forloop.counter|stringformat:"s" %}
{% with template="mod"|add:y|add:".html" %}
<p>{{ template }}</p>
{% endwith %}
{% endwith %}
{% endfor %}

结果为:

<p>mod1.html</p>
<p>mod2.html</p>
<p>mod3.html</p>
<p>mod4.html</p>
<p>mod5.html</p>
<p>mod6.html</p>

第二个WITH标记是必需的,因为字符串格式标记是用一个自动前缀实现的。%为了绕过这个问题,您可以创建一个自定义过滤器。
过滤器:http://djangosnippets.org/nippers/393/

简单的过滤器

我经常使用此过滤器,以减少模板的混乱情况。代替:

{%if some_variable%}, {{some_variable}}{%endif%}
我可以写:

{{some_variable|format:", %s"}}
我常用的一种是:

{{some_variable|format:"<p>%s</p>"}}

1.从Django导入 模板
2.注册 = 模板。图书馆()

def format (value , arg ):
"""
更改默认过滤器” stringformat“而不在其前面添加%,
因此可以将该变量放置在字符串中的任何位置。
"""
try :
if value :
return (unicode (arg )) % value
else
返回 u''
(除了 (ValueError , TypeError )):
返回 u''
寄存器。过滤器('format'

将snipped保存为some_app/templatetags/some_name.py

from django import template

register = template.Library()

def format(value, arg):
"""
Alters default filter "stringformat" to not add the % at the front,
so the variable can be placed anywhere in the string.
"""
try:
if value:
return (unicode(arg)) % value
else:
return u''
except (ValueError, TypeError):
return u''
register.filter('format', format)

模板

{% load some_name.py %}

{% for x in some_list %}
{% with template=forloop.counter|format:"mod%s.html" %}
<p>{{ template }}</p>
{% endwith %}
{% endfor %}

二、基本操作:

1.当列表为空或者非空时执行不同操作:

{% for item in list %}
...
{% empty %}
...
{% endfor %}

2.forloop.counter从1开始计数,forloop.counter0 从0开始计数,reversed 逆向计数

{% for item in list %}
...
{{ forloop.counter }}
...
{% endfor %}

{% for item in list %}
...
{{ forloop.counter0 }}
...
{% endfor %}

{% for item in list reversed %}
{{ item }}
{% endfor %}

  1. 判断第一次好最后一次

{% for item in list %}
...
{% if forloop.first %}
This is the first round.
{% endif %}
...
{% endfor %}

{% for item in list %}
...
{% if forloop.last %}
This is the last round.
{% endif %}
...
{% endfor %}


举报

相关推荐

0 条评论