Django template split a string in two parts

Viewed 2148

In my Django project i hae to split a string into a template based on a specific char.

str1 = "Part1 - Part2"

in pure python I would do it like this:

part1 = str1.split("-",1)[0]
part2 = str1.split("-",1)[1]

using django template instead i try:

{{ str1|split:'-'|first }}

but i give an error:

Invalid filter: 'split'

Someone can help me for split my variable ina django template and take just the first or second part based on a specific char?

So many thanks in advance

2 Answers

using templatetags split would be something like this:

as templatetags only takes one argument, but for split with max limit we need to pass two arguments. in such case we can combind the two arguments as a string and use a separator. here for example i'm using |||| as two arguments separator

in your app folder create one folder, named templatetags

there create a file split.py :

from django import template
register = template.Library()

@register.filter
def split(splitable, split_at):
    # split with max limit
    if len(split_at.split("||||")) == 2:
        return splitable.split(split_at.split("||||")[0], int(split_at.split("||||")[1]))
    
    # normal split without max limitation
    return splitable.split(split_at)

now it's better to restart your server once.

then in template do:

{% load split %}

<!-- first element no split limit -->
{{ str1|split:"-"|first }}

<!-- first element with split limit, in following example, the limit is 1 -->
{{ str1|split:"-||||1"|first }}

<!-- last element no split limit -->
{{ str1|split:"-"|last }}

<!-- last element with split limit, in following example, the limit is 1 -->
{{ str1|split:"-||||1"|last }}

<!-- element by index no split limit -->
{% with str1|split:"-" as split_data %}{{ split_data.0 }}{% endwith %}

<!-- element by index with split limit, in following example, the limit is 1 -->
{% with str1|split:"-||||1" as split_data %}{{ split_data.0 }}{% endwith %}

In Your Template you need to directly use the converted value because there is no way filter to split text in templates

{{ part1 }} {{ part2 }}
Related