Meteor / Blaze - Simple concatenated string in parameter
I know how to do this with a more advanced and probably "correct" method, but I was wondering if there are easier ways to do this.
{{> alert message="My message"}}
Basically, I have a template that takes a value message
. I want to send him a message Logged in as: samanime
where samanime
is any value currentUser.username
.
I know I can do this by creating a helper to combine the two parts for me, but is there a way I can do this without an extra helper? Maybe something like:
{{> alert message="Logged in as: ${currentUser.username}"}}
source to share
After playing around with a few ideas, I think I came up with a sensible solution that doesn't break (too much) the separate look and feel.
First, to do the actual concatenation, I made a helper concat
:
// Takes any number of arguments and returns them concatenated.
UI.registerHelper('concat', function () {
return Array.prototype.slice.call(arguments, 0, -1).join('');
});
Usage example:
{{ concat "a" "b" "c" }}
{{! output: "abc" }}
Then I created a new sub-unit withResult
:
Helper:
UI.registerHelper('withResult', function () {
Template._withResult.helpers({result: this.valueOf()});
return Template._withResult;
});
Template:
<template name="_withResult">
{{> UI.contentBlock result=result}}
</template>
Usage example:
{{#withResult concat "a" "b" "c"}}
{{> alert message=result}}
{{/withResult}}
Basically, it takes the result of any call to the block (in this case, concat) and places it in a variable result
accessible to the template.
I think this is a pretty clean and flexible way to not only concat, but also get other simple values of a few parameters. The only downside at this stage is that it only allows one variable to be created (since each scope puts it in the same place) However, this can be overcome if other helpers return objects.
Of course, this is something you don't want to overuse, as it blurs the clean line we're trying to keep between presentation and logic.
source to share