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条回答
倾城 Initia
2楼-- · 2019-06-16 02:42

You could do a slightly more reusable solution like so:

module.exports = function (json) {
  var concat = '';
  var flipArray = [];
  for(var key in json.hash){
    flipArray.push(json.hash[key]);
  }

  for(var i = (flipArray.length - 1); i >= 0; i--){
    concat += flipArray[i];
  }

  return concat;
};

Then call it like so:

{{> icon name=(concat a="file-" b="pdf")}} // passes file-pdf to the partial under the hash value name

or

{{concat a="icon-" b="pdf" c="-Asdfasd" d="zxcvzxcvzxcvxz"}} // outputs icon-pdf-Asdfasdzxcvzxcvzxcvxz

The reason for the looping backwards in the helper is because handlebars currently lists it's hash parameters from last to first from the order you declare them.

查看更多
登录 后发表回答