本文介绍了自定义django标签返回列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个自定义标签,以返回一个列表,然后可以使用 {%为custom_tag_returning_list%}中的商品进行浏览.

I'd need to create a custom tag returning a list I can then walk through with {% for item in custom_tag_returning_list %} .

现在,我已经使用* assign_tag *方法进行了以下破解,但是怀疑这是否是正确的方法:

Now I've made a following hack using *assign_tag* method, but doubt if it's the right way:

from django import template
from product.models import Product

register = template.Library()

@register.assignment_tag
def all_products():
    return Product.objects.all().order_by('name')

在模板中,我不能直接使用 all_products ,但需要首先分配一些变量:

In a template I cann't use all_products directly but need to assign to some variable first:

{% all_products as all_products_list %}
{% if all_products_list %}
  {% for product in all_products_list %}
   ...
  {% endfor %}
{% endif %}

是否需要对临时变量进行赋值?不能直接与其他标记助手一起使用吗?

Is it necessary to do an assignment to a temporary variable ? Cann't be used directly with some other tag helper ?

推荐答案

这对我来说似乎很好.

或者,由于某种原因,如果您无法通过视图的上下文传递 product_list ,则可以使用包含标签,如果您觉得更干净:

Alternatively, for some reason if you cannot pass the product_list through the view's context, you can use an inclusion tag if you feel that is cleaner:

@register.inclusion_tag("tags/products_list.html")
def all_products():
    return {'products_list': Product.objects.order_by('name') }

products_list.html

products_list.html

{% for product in products_list %}
   .........
{% empty %}
  Empty list
{% endfor %}

在html文件中,您只需

and in the html file, you would just do

{% all_products %}

这篇关于自定义django标签返回列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:35