How to remove } character from liquid string

Viewed 847

In Liquid, one can remove a character X from a liquid string like so,

{{ 'random_string' | remove:'X' }}

E.g. the { character can be removed in this way.

However, removing the } character this way gives the following error,

Liquid syntax error (line 15): Variable '{{ 'random_string' | remove:"}' was not properly terminated with regexp: /\}\}/

Which probably has to do with the usage of the } character in the Liquid language.

Question

How do I remove the } character from the string?

2 Answers

One solution would be using the url_encode filter, then removing the encoded string:

{% capture my_variable %}hello}}worl}d{% endcapture %}
{{ my_variable | url_encode | remove: "%7D"}}

First, create your own tag.

<project>/<app>/templatetags/clean_string.py

Insert this code into it.

import re

from django import template
register = template.Library()


@register.filter
def clean_string(value):
    regex = '[^-_.,!?@%\w\d]+'
    return re.sub(regex, '', value)

After that, register it in the settings...

<project>/<projectName>/settings.py

'OPTIONS': {
            'context_processors': [
                ...
            ],
            'libraries': {
                'clean_string': '<project>.templatetags.clean_string'
            }
        },

At the beginning of your .html template Add tag loading

{% load clean_string %}

This filter can be applied to any string.

For example:

{{ '[tes{t}!'|clean_string }}

The filter can be adjusted in a variable ...

regex = '[^-_.,!?@%\w\d]+'

Output:

test!

Related