Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of using Handlebars lookup helper

Handlebars has a built-in helper called lookup. The documentation is not very clear about how it works. Could I see an example?

like image 220
Tamlyn Avatar asked Apr 23 '15 16:04

Tamlyn


People also ask

How do I register Handlebars in Helper?

Handlebars. registerHelper("noop", function(options) { return options. fn(this); }); Handlebars always invokes helpers with the current context as this , so you can invoke the block with this to evaluate the block in the current context.

How do you iterate objects in Handlebars?

To iterate over an object with JavaScript and Handlebars. js, we can use the #each keyword. to add the Handlebars script and the template for looping through each entry in data . We use #each this to loop through each array property.

How do you use unless Handlebars?

You can use the unless helper as the inverse of the if helper. Its block will be rendered if the expression returns a falsy value. If looking up license under the current context returns a falsy value, Handlebars will render the warning. Otherwise, it will render nothing.


2 Answers

Sure, past me! Here's an example from your future.

Suppose you have an object or array obj and a variable field and you want to output the value of obj[field], you would use the lookup helper {{lookup obj field}}.

The code defining the helper is simply:

function(obj, field) {
  return obj && obj[field];
}
like image 167
Tamlyn Avatar answered Oct 17 '22 10:10

Tamlyn


The lookup property is useful if we don't know the name of the property we want, for instance because it's in a variable or the result of an expression.

If we have this object:

var book = {
    title: 'Discovery of Heaven'
};

We could put this in the HTML like this:

<p>{{book.title}}</p>

Which is equivalent to:

<p>{{lookup book 'title'}}</p>

Maybe we don't know that we want the title. Say the property name is somewhere in a variable instead:

var property = 'title';

Now we could show the book title like this:

<p>{{lookup book property}}</p>
like image 25
Bart S Avatar answered Oct 17 '22 10:10

Bart S