1

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>
Braj
  • 46,415
  • 5
  • 60
  • 76

1 Answers1

0

take a look on this answers: Pass JavaScript object/hash to Handlebars helper? use only options in your helper, add text=title in template and pass text to SafeString.

Community
  • 1
  • 1
Marek Ka.
  • 327
  • 3
  • 14
  • Yes I can pass one more option in the function as extra argument and that will solve this problem. I am just learning it and trying different options. – Braj Dec 09 '14 at 10:25