I am new to Handlebar.js and trying to learn it. I have a scenario where I want to insert handlebar expression inside the extra options.
In below sample code I want to set the title of each link based on its text for example "Click to go Google"
This is what I have tried but no one is working:
title="Click to go (this.text)"
title="Click to go this.text"
title="Click to go "+this.text
Data:
var links=[
{text:"Google",url:"http://www.google.com"},
{text:"Yahoo",url:"http://www.yahoo.com"}
];
Sample code:
<script type="x-handlebars-template" id="links">
{{#each this}}
{{link url text title="Click to go (this.text)"}}<br>
{{/each}}
</script>
Complete code:
Links:
<div class="links"></div>
<script type="text/javascript">
Handlebars.registerHelper("link",function(url,text,options){
var attrs=[];
for(var attr in options.hash){
attrs.push(attr+"=\""+options.hash[attr]+"\"");
}
var escapedURL=Handlebars.escapeExpression(url);
return new Handlebars.SafeString('<a href=\"'+escapedURL+'\"'+attrs+'>'+text+'</a>')
});
</script>
<script type="x-handlebars-template" id="links">
{{#each this}}
{{link url text title="Click to go (text)"}}<br>
{{/each}}
</script>
<script type="text/javascript">
var links=[
{text:"Google",url:"http://www.google.com"},
{text:"Yahoo",url:"http://www.yahoo.com"}
];
var template=Handlebars.compile($("#links").html());
$(".links").append(template(links));
</script>