how to split the string in django template?
Asked Answered
B

4

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

Bibulous answered 30/1, 2017 at 9:36 Comment(1)
Possible duplicate of : #8318037Nishanishi
W
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 %}
Willwilla answered 31/1, 2017 at 9:26 Comment(2)
It doesn't work due to error Invalid filter: 'split'. Another solution: https://mcmap.net/q/333032/-django-templates-split-string-to-array.Lemoine
Hum.. did you create the filter in your code? Because split is a custom filter.Willwilla
P
3

For extract character string, use filter cut:

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

this removes the scripts from the string.

Phenobarbitone answered 27/9, 2018 at 3:24 Comment(0)
S
3

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

Scholium answered 13/5, 2023 at 19:11 Comment(0)
Y
-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 %}
Yaya answered 20/3, 2020 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.