Search code examples
nunjucks

How to replace a character in a string using nunjucks


I am trying to remove some characters from a string in a nunjucks template file. The string that I am trying to manipulate is:

"swatch_dark_&_stormy"

Is there a simple way to remove the & without having to create a filter method? I know I can do this with a filter, but I am hoping there is a built in method that I could use instead.

Macro implementation so far:

{% macro filterSwatchClass(swatchCSSClassName) %}
    {%set cssClassName = swatchCSSClassName | cleanCSSClassName%}
    {{"swatch_"+cssClassName}}
{% endmacro %}

Filter that does the job:

env.addFilter('cleanCSSClassName', function(string){
        return string.replace(/&/g,"").replace(/__/g,"_");
    })

Solution

  • Try:

    {% macro filterSwatchClass(swatchCSSClassName) %}
        {%set cssClassName = swatchCSSClassName | cleanCSSClassName %}
        {{"swatch_"+cssClassName | replace("&", "")}}
    {% endmacro %}
    

    See replace on nunjucks docs for more info.