Handlebars - Concat string parameters when calling

2019-06-16 01:57发布

I would like to know if it is possible to concat a variable with another string when loading a partial using Handlebars.

{{partial logos this ns=../ns nsr=../nsr id=id+"something"}}

I'd like to concat id+"something" and storing it into id, which would be sent to the template.

I'm using a custom helper to load partials (partial) which merge this with the options.hash provided by handlebars.

7条回答
We Are One
2楼-- · 2019-06-16 02:22

If you're doing a simple a + b concatenation and you're already including handlebars-helpers, you can use the add helper:

{{> myPartial myVariable=(add someVariable "some string") }}
查看更多
劳资没心,怎么记你
3楼-- · 2019-06-16 02:26

In ES6 this is possible using this helper: concat : (...strs) => strs.join('')

You may also want to skip parameters given by Handlebars, which is: concat : (...strs) => strs.filter( arg => typeof arg !== 'object' ).join('')

查看更多
劳资没心,怎么记你
4楼-- · 2019-06-16 02:27

Try following. Link helper is my own helper for adding context path /us

Handlebars.registerHelper('link', function(option,parameter) {
            return '/us' + option.hash.target;
        });

Handlebars.registerHelper('concat', function() {
            var outStr = '';
            for(var arg in arguments){
                if(typeof arguments[arg]!='object'){
                    outStr += arguments[arg];
                }
            }
            return outStr;
        });

Then I have called like this. My url having puppies

{{link target=(concat '/' url)}}

Then finally i got output like this /us/puppies

查看更多
祖国的老花朵
5楼-- · 2019-06-16 02:35

There is a way actually. I've tried with default partial loader ">", but I hope it should work with "partial" too.

You can write a helper like this

Handlebars.registerHelper( 'concat', function(path) {
    return "/etc/path" + path;
});

and Call it like

{{> responsive-image src=(concat '/img/item-tire.png') alt="logo" }}

I hope that helps.

查看更多
走好不送
6楼-- · 2019-06-16 02:38

Here's an easier way. A helper named 'concat':

module.exports = function(){
  var arg = Array.prototype.slice.call(arguments,0);
  arg.pop();
  return arg.join('');
};

To be used as:

{{>myPartial id=(concat "foo" myVar myOtherVar)}}
查看更多
男人必须洒脱
7楼-- · 2019-06-16 02:39

No, this is not possible. Use concatenation inside your helper.

{{partial logos this ns=../ns nsr=../nsr idKey=id idValue="something"}}
查看更多
登录 后发表回答