[Answered ]-How to split a string inside of django template

1๐Ÿ‘

โœ…

Ok so first in your app directory create a file called filters.py and add this to it:

from django import template
from django.template.defaultfilters import stringfilter


register = template.Library()


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

Then go to your settings.py and add this to the TEMPLATES:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'libraries': { # <----- add this
                'filter_tags': 'your_app_name_here.filters' # switch with your app name
            }
        },
    },
]

Then in your template:

{% load filter_tags %}

{% with wizard.form.tags|split:"," as tags %}
    {% for tag in tags %}
        {{ tag }}<br>
    {% endfor %}
{% endwith %}
๐Ÿ‘คSLDem

Leave a comment