简体   繁体   中英

Get values from template in handlebars helper

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.

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM