how to split the string in django template?

24,291

Solution 1

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

Solution 2

For extract character string, use filter cut:

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

this removes the scripts from the string.

Share:
24,291
Akhi
Author by

Akhi

Updated on September 23, 2021

Comments

  • Akhi
    Akhi almost 3 years

    i am trying to split the string in template using custom template filter. But i got an error

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

    Here it is my filter

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

    this is my template

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

    Thanks

  • Marat Gareev
    Marat Gareev almost 3 years
    It doesn't work due to error Invalid filter: 'split'. Another solution: stackoverflow.com/a/8318915/5494506.