2012-06-25 40 views

回答

1

快速而醜陋的黑客得到這個工作將使用make_list過濾器:

{% for i in "xxxx"|make_list %} 
    {{ image_html }} 
{% endfor %} 

這將打印圖像四次(因爲有字符串中的4個字符)。

一個清潔的方法是使用range()傳遞一個列表到您的模板:

context['image_print_range'] = range(1, 5) 
... 
{% for i in image_print_range %} 
    {{ image_html }} 
{% endfor %} 

另一種解決方案(可能是最乾淨的一個)是一個自定義模板標籤或過濾器,例如:

@register.simple_tag 
def print_multiple(value, count): 
    """Print a value multiple times.""" 
    return ' '.join([value] * count) 

並在您的模板中:

{% print_multiple "foobar" 4 %} 
1

要麼將​​其添加到視圖中的列表中x次,以便在{% for %}標記中迭代它,要麼創建custom template tag以重複圖像url x次。