Tuesday, July 8, 2014

Simpler Lodash Templates

I used to use Lodash template() until I give up due to the verbosity of the interpolation delimiters used. They're a pain, especially when it's a simple string I want to build. Stylistically, I don't want to resort to string concatenation in my code, but, it turned out to be the better option. You can use Lodash for simple string-building scenarios such as these — it just requires a little tweaking.

There's a bunch of options, in addition to the template data itself, that you can pass to template(). This can potentially alter the way the template is interpreted and rendered. For example, here's a basic string interpolation function that uses template().

function s( text, data ) {
    return _.template( text, data, {
        interpolate: /\{\{([\s\S]+?)\}\}/g
    });
}

s( 'hello, {{greeting}}', { greeting: 'world' } );

Here we've created a simple function called s(). It's potentially confusing name stands for string, but the trade-off is that it's tiny, and potentially used everywhere. This function basically wraps a call to template(). The main change we're introducing is to the template syntax — {{name}} — the new simpler way to specify variables. The object containing the substitution data is passed as usual. We can just return the result, since passing in the substitution data renders the string and returns it, as opposed to compiling and returning a function.

No comments :

Post a Comment