Search code examples
javascripttemplatesreplacehandlebars.jshelper

Removing <br> from Handlebars Template


I have a template that is populated from a database driven by a CMS. A CMS where the people that enter in the data don't really know HTML, they just say they do. So they'll enter in a series of break tags (incorrectly, mind you) instead of just wrapping their content in a paragraph.

I am then importing all of that into a neat little template, and using that data to populate data-labels to display on buttons, and other stuff.

I've seen a few Handlebars Helpers that say they do a find and replace, but I have no idea how to write the syntax IN my template to compile it with grunt without it flagging errors. Here's the helper I wanted to use:

Handlebars.registerHelper('replace', function( find, replace, options) {
    var string = options.fn(this);
    return string.replace( find, replace );
});

Now this looks pretty straight forward, but there's no documentation on how to actually toss the stash in your template other than {{#replace}}

The parameter I'm trying to look through is {{caption}} and I'm looking for ever instance of '
' and replace it with ''.

When I write the stash like this: {{#replace '<br>', ' ', caption}}, but then I get a parse error.


Solution

  • I'm not sure that you would want to use a block helper in this situation. I think the following regular helper would do:

    Handlebars.registerHelper('replace', function (find, replace, context) {
        return context.replace(new RegExp(find, 'g'), replace);
    });
    

    Note that I am using a RegExp so that we can replace all instances of the find text.

    You would then use this helper within your template in the following way:

    {{replace '<br>' ' ' caption}}