Python 用于循环的 Django 模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18487919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:52:34  来源:igfitidea点击:

Django template for loop

pythonhtmldjangodjango-templates

提问by Nielsen Ramon

I have a template where I get certain variables back. One variable is instance.category which outputs: "words words words" which are values split by spaced.

我有一个模板,可以在其中获取某些变量。一个变量是 instance.category ,它输出:“words words words”,它们是按间距分割的值。

When I use the code below I get letter by letter back and not the words.

当我使用下面的代码时,我会逐个回复,而不是单词。

{% for icon in instance.category  %}
  <p>{{ icon }}</p>
{% endfor %}

Output

输出

<p>w</p>
<p>o</p>
<p>r</p>
<p>d</p>
<p>w</p>
....

I need:

我需要:

<p>word</p>
<p>word</p>
<p>word</p>

The Django plugin code

Django插件代码

from cmsplugin_filer_image.cms_plugins import FilerImagePlugin
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _
from models import Item

class PortfolioItemPlugin(FilerImagePlugin):
    model = Item
    name = "Portfolio item"
    render_template = "portfolio/item.html"
    fieldsets = (
        (None, {
            'fields': ('title', 'category',)
        }),
        (None, {
            'fields': (('image', 'image_url',), 'alt_text',)
        }),
        (_('Image resizing options'), {
            'fields': (
                'use_original_image',
                ('width', 'height', 'crop', 'upscale'),
                'use_autoscale',
            )
        }),
        (_('More'), {
            'classes': ('collapse',),
            'fields': (('free_link', 'page_link', 'file_link', 'original_link', 'target_blank'),)
        }),
    )

plugin_pool.register_plugin(PortfolioItemPlugin)

Any help is appreciated!

任何帮助表示赞赏!

采纳答案by augustomen

If your separator is always " "and categoryis a string, you don't actually need a custom template filter. You could simply call splitwith no parameters:

如果你的分隔符始终" "category是一个字符串,你实际上并不需要自定义模板过滤器。您可以简单地split不带参数调用:

{% for icon in instance.category.split %}
  <p>{{ icon }}</p>
{% endfor %}

回答by alecxe

You are passing a string instance.categoryinto the template and then iterating over its chars.

您将一个字符串传递instance.category到模板中,然后迭代它的字符。

Instead, pass a list to the template: instance.category.split()which will split your words words wordsstring into the list ['words', 'words', 'words']:

相反,将列表传递给模板:instance.category.split()这会将您的words words words字符串拆分为列表['words', 'words', 'words']

>>> s = "words words words"
>>> s.split()
['words', 'words', 'words']


Or, you can define a custom filterthat will split a string into the list:

或者,您可以定义一个自定义过滤器,将字符串拆分为列表:

from django import template
register = template.Library()

@register.filter
def split(s, splitter=" "):
    return s.split(splitter)

Then, use it in the template this way:

然后,以这种方式在模板中使用它:

{% for icon in instance.category|split %}
    <p>{{ icon }}</p>
{% endfor %}