【问题标题】:how to split the string in django template?如何在 django 模板中拆分字符串?
【发布时间】:2017-06-15 10:00:41
【问题描述】:

我正在尝试使用自定义模板过滤器拆分模板中的字符串。但是我遇到了错误

    TemplateSyntaxError at /job/16/
'for' statements should use the format 'for x in y': for skill in form.instance.skills | split : ","

这是我的过滤器

@register.filter(name='split')
def split(value, key):
    """
        Returns the value turned into a list.
    """
    return value.split(key)

这是我的模板

<h4>Skills</h4>
        {% for skill in form.instance.skills | split : "," %}
            {{ skill }}
          {% endfor %}

谢谢

【问题讨论】:

标签: django-templates django-filter django-1.5


【解决方案1】:
<h4>Skills</h4>
{% with form.instance.skills|split:"," as skills %}
    {% for skill in skills %}
        {{ skill }}<br>
    {% endfor %}
{% endwith %}

【讨论】:

【解决方案2】:

对于提取字符串,使用过滤切割:

<a href="tel://+1{{ phone|cut:'-' }}">Phone</a>

这会从字符串中删除脚本。

【讨论】:

    【解决方案3】:

    直接 for 循环也可以,您只需删除语法中的空格:

        <h4>Skills</h4>
                {% for skill in form.instance.skills|split:"," %}
                    {{ skill }}
                  {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2021-04-16
      • 2020-11-11
      • 2012-01-09
      • 2016-06-02
      • 1970-01-01
      • 2011-05-22
      • 2016-10-30
      • 2011-04-29
      相关资源
      最近更新 更多