15

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

Akhi
  • 221
  • 1
  • 3
  • 14

4 Answers4

6

Split is a custom filter, don't forget to create your filter, and to load it in your HTML page. Documentation for Django 4.0: https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/

<h4>Skills</h4>
{% with form.instance.skills|split:"," as skills %}
    {% for skill in skills %}
        {{ skill }}<br>
    {% endfor %}
{% endwith %}
Wilfried
  • 1,623
  • 1
  • 12
  • 19
3

For extract character string, use filter cut:

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

this removes the scripts from the string.

1

I was looking around for how to use split filter in Django and i had difficulty to know how to create and register a filter. I tried many solutions till I was able to create a split filter, I am posting here how to do it

In views.py

from django.template.defaulttags import register

@register.filter(name='split')
def split(value, key): 
 
    value.split("key")
    return value.split(key)

and then use it in your HTML as mentioned in the previous very good answers

Hope this helps

reference: https://gist.github.com/linuxkathirvel/8127c40fdad028bbb79bec24f36eee1c

Emad Kamel
  • 11
  • 3
-1

The direct for loop works too, you just have to remove the spaces in the syntax:

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