I want to use one helper function in another helper function. In below code I want to highlight last name if it contains "Finch" word. I have writtern helper class for that. If we use in hbs file then syntax would be {{highlight name}}. But how to use it since I have to use it in another helper class.
Below is my code:
Handlebars.registerHelper('fullName', function(person) {
return person.firstName + " " + person.lastName;
});
Handlebars.registerHelper('highlight', function(person) {
var item = (person.lastName).replace('Finch', '<span style="color: red">'
+ Finch + '</span>');
return new Handlebars.SafeString(item);
});
Here is the working fiddle : http://jsfiddle.net/wC6JT/4/
Here is the fiddle where "highlight" helper is called.: http://jsfiddle.net/wC6JT/3/ . This will not produce any results since we will get console errors for person.lastName not recognized in "highlight" register helper.
I want to use "highlight" helper in fullname helper for person.lastName. How can this be acheived.
To call another function in the same helper, use the syntax: this. methodName , where this is a reference to the helper itself. For example, helperMethod2 calls helperMethod3 with this code.
To implement the helper, we write a JavaScript function that takes its arguments as an array. This is because helpers can also receive named arguments, which we'll discuss next. import { helper } from '@ember/component/helper'; function substring(args) { let [string, start, end] = args; return string.
To call a Handlebars helper from another function, you can use Handlebars.helpers
:
Handlebars.registerHelper('fullName', function(person) {
var lastName = Handlebars.helpers.highlight.apply(this, [person.lastName]);
var firstName = Handlebars.Utils.escapeExpression(person.firstName);
return new Handlebars.SafeString(firstName + " " + lastName);
});
Handlebars.registerHelper('highlight', function(str) {
var safeStr = Handlebars.Utils.escapeExpression(str);
var item = safeStr.replace("Finch", "<em>Finch</em>");
return new Handlebars.SafeString(item);
});
Here is a working fiddle: http://jsfiddle.net/acLcsL6h/1/
Read this blog post for another example.
Extract the contents of the method you want to use in the first method into its own javascript method. Then call that javascript method in both helpers as necessary.
You can't do it unless you refactor the contents of one of the methods into its own javascript method.
So in your case it should look something like this:
Handlebars.registerHelper('fullName', function(person) {
return person.firstName + " " + highlightJavascript(person);
});
Handlebars.registerHelper('highlight', highlightJavascript);
highlightJavascript : function(person) {
var item = (person.lastName).replace('Finch', '<span style="color: red">'
+ Finch + '</span>');
return new Handlebars.SafeString(item);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With