Get values from template in handlebars helper

2019-08-03 10:32发布

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.

2条回答
Deceive 欺骗
2楼-- · 2019-08-03 11:14

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.

查看更多
混吃等死
3楼-- · 2019-08-03 11:21

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);
});
查看更多
登录 后发表回答