Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split the string in django template?

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

like image 345
Akhi Avatar asked Jan 30 '17 09:01

Akhi


People also ask

How do you split a string in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Which Django template syntax allows to use the for loop?

There's a single Django template tag for looping: {% for %} . It uses a similar syntax to Python's for statement and provides some built-in variables that give information about where you are in the iteration. Lines 7 to 11 contain a {% for %} block, which is similar to the for keyword in Python.

What are templates in Django?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


2 Answers

For extract character string, use filter cut:

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

this removes the scripts from the string.

like image 73
Diego Santa Cruz Mendezú Avatar answered Sep 27 '22 19:09

Diego Santa Cruz Mendezú


<h4>Skills</h4>
{% with form.instance.skills|split:"," as skills %}
    {% for skill in skills %}
        {{ skill }}<br>
    {% endfor %}
{% endwith %}
like image 27
Wilfried Avatar answered Sep 27 '22 21:09

Wilfried