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

一、高级操作

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 %}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值