django的with标签

  1. 使用方法:
{% with comments.count as total_comments %}
	<h2>
	{{ total_comments }}
	</h2>    
{% endwith %}

{% with %}标签可将某个值赋予可用的新变量中,直至遇到{% endwith %}标签。


但是,不能在with标签中再使用自定义模板标签
如下:

# 其中get_most_commented_posts是自定义的模板标签
{% with get_most_commented_posts as most_commented_posts %}
    <ul>
        {% for post in most_commented_posts %}
        <li>
        <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </li>
        {% endfor %}
    </ul>
{% endwith %}
# 结果发现 无法遍历数据

正确的用法时:
# 使用as参数
{% get_most_commented_posts as most_commented_posts %}
    <ul>
        {% for post in most_commented_posts %}
        <li>
        <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </li>
        {% endfor %}
    </ul>

下面介绍一下with参数:
{% include 'pagination.html' with page=posts %}

作用是将posts赋值给page变量,并将page变量传递给模板pagination.html

总结:标签中不能嵌套其他标签,可使用相关参数,如as参数,with参数等
注:使用{% with %}模板标签对于防止多次计算QuerySet十分有用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值