【问题标题】:How to split a string inside of django template如何在 django 模板中拆分字符串
【发布时间】:2021-04-16 19:21:20
【问题描述】:

我正在使用 javascript 向 django 模板传递一个由逗号分隔的字符组成的字符串,例如 A, B, C, ..

这是我的代码:

 {% with list_of_words = wizard.form.tags.split(',') %}
    {% for tag in list_of_words  %}
      <a href="" ><span class="btn btn-outline-primary btn-xs mb-3">
        <span class="h6 text-uppercase">
          <div class="badge badge-rounded-circle badge-danger-soft mt-1 mr-0">
            <i class="fe fe-check"></i>
          </div>
          {{ tag }}
          </span></span></a>
    {% endfor %}
{% endbwith %}

其中{{wizard.form.tags}} 返回一个长字符串,但是我需要在模板内将其分开以设置样式。有解决办法吗?

附:请注意,我可能无法向模型添加方法,因为 {{wizard.form.tags}} 中的值是由 js 传递的,而不是从数据库中读取的。

【问题讨论】:

    标签: django


    【解决方案1】:

    好的,首先在您的应用目录中创建一个名为filters.py 的文件并将其添加到其中:

    from django import template
    from django.template.defaultfilters import stringfilter
    
    
    register = template.Library()
    
    
    @register.filter(name='split')
    @stringfilter
    def split(value, key):
        """
            Returns the value turned into a list.
        """
        return value.split(key)
    

    然后转到您的 settings.py 并将其添加到 TEMPLATES

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'libraries': { # <----- add this
                    'filter_tags': 'your_app_name_here.filters' # switch with your app name
                }
            },
        },
    ]
    

    然后在你的模板中:

    {% load filter_tags %}
    
    {% with wizard.form.tags|split:"," as tags %}
        {% for tag in tags %}
            {{ tag }}<br>
        {% endfor %}
    {% endwith %}
    

    【讨论】:

    • 谢谢,但它给出了一个错误:第 126 行的块标记无效:'set',预期的 'endblock'。您是否忘记注册或加载此标签?
    • 我只是替换了代码,但给出了同样的错误
    • 显示您要传递的字符串,它是包含在wizard 还是wizard.form.tags 中?
    • 就像A, B, C,....,我也试过{% set list_of_words = wizard.form.tags.split(',') %}。我正在尝试将其替换为 with
    • 你能用你当前的代码更新你的问题吗?
    猜你喜欢
    • 2017-06-15
    • 2020-11-11
    • 2012-01-09
    • 2016-06-02
    • 1970-01-01
    • 2011-05-22
    • 2016-10-30
    • 2011-04-29
    相关资源
    最近更新 更多