Search code examples
meteormeteor-blazespacebars

Meteor/Blaze - Simple string concatenate in parameter


I know how to do this via the more expanded, and probably "proper" method, but I was wondering if there are any simpler ways to do this.

{{> alert message="My message"}}

Basically, I have a template that takes a value message. I want to give it the message Logged in as: samanime, where samanime is whatever the value of currentUser.username.

I know I can do this by creating a helper to concatenate the two parts for me, but is there some way that I can do it without an extra helper? Maybe something like:

{{> alert message="Logged in as: ${currentUser.username}"}}

Solution

  • After playing around with a couple ideas, I think I've come up with a reasonable solution that doesn't violate (too much) the separate of view and logic.

    First, to do the actual concatenation, I made a concat helper:

    // Takes any number of arguments and returns them concatenated.
    UI.registerHelper('concat', function () {
        return Array.prototype.slice.call(arguments, 0, -1).join('');
    });
    

    Example usage:

    {{ concat "a" "b" "c" }}
    {{! output: "abc" }}
    

    Then, I made a new block helper, withResult:

    Helper:

    UI.registerHelper('withResult', function () {
        Template._withResult.helpers({result: this.valueOf()});
        return Template._withResult;
    });
    

    Template:

    <template name="_withResult">
        {{> UI.contentBlock result=result}}
    </template>
    

    Example usage:

    {{#withResult concat "a" "b" "c"}}
        {{> alert message=result}}
    {{/withResult}}
    

    Basically, it takes the result of whatever is the block call (in this case, concat) and puts it in the variable result available to the template.

    I think this is a fairly clean and flexible way to not only concat, but also to get other simple multiple-parameter values across. The only negative at this point is it only allows you to create one variable (as each scope puts it in the same spot). However, that can be overcome by having other helpers return objects.

    Of course, this is something that you don't want to abuse, as it would blur the clean line that we try to keep between view and logic.