Get values from template in handlebars helper

蹲街弑〆低调 提交于 2019-12-11 07:14:29

问题


I am using Handlebars for my template. Is there a way to use the values from a template where the helper is in use ?

It is important that the given value is a string and later be the value.

Example:

// Template.html
<p>{{myHelper 'This is an awsome {name}'}}</p>

Helper.js
Handlebars.registerHelper('myHelper', function(string){

 // string is 'This is an awsome {name}' AND it is important that {name} is a string and at this point not the real value

 var myNewString = string.replace(\{name}\, Handlebars.getValueByKey(name));
 return myNewString

});

If name is "Test" the returned value will be This is an awsome Test

The value for name is given in another Helper for this template, where is defined that "name" is "Test" as a string.

I am looking for a function something like i used in my example - getValueByKey

Is there a typical way to do this ? I did not find anything like this in the offical documentation.

Edit: I am sorry - i dont know why the example in the code-box looks like this.


回答1:


You're close. The key is in passing in exactly what you want to the template:

// Template.html
<p>{{myHelper 'This is an awesome' name}}</p>

Helper.js
Handlebars.registerHelper('myHelper', function(string, name){

  // string is 'This is an awesome'
  // value of {name} is passed as another value
  // If you wanted to do other things with the {name} you could
  // do that in the function below

  var myNewString = string + name;
  return myNewString

});

Hope that's closer to what you were looking for.




回答2:


Typically you would just setup a generic helper that would return whatever values you need. But you need to pass in the values you want in the helper. If you need more than one simply pass in the extra values by name. For example

<p>My name is {{name}}</p>
<p>My Phone number is {{phonenumber}}</p>
<p>My Address is {{address}}</p>
<p>The length of all three are {{stringLength name phonenumber address}}</p>

Handlebars.registerHelper('stringLength', function(name, phonenumber, address) {
    var retVal = name + phonenumber + address;
    return new Handlebars.SafeString(retVal.length);
});


来源:https://stackoverflow.com/questions/23016344/get-values-from-template-in-handlebars-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!