Example of using Handlebars lookup helper

天涯浪子 提交于 2019-12-09 02:08:52

问题


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


回答1:


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

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

The code defining the helper is simply:

function(obj, field) {
  return obj && obj[field];
}



回答2:


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>


来源:https://stackoverflow.com/questions/29829723/example-of-using-handlebars-lookup-helper

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