user3270303
user3270303

Reputation:

Handlebars.js issue regarding the helper

I have created the helper to generate the "li" code as below:

Handlebars.registerHelper("REQUEST_LI", function(id){
                                    var LI = "";
                $.each(APP.que_random_ids, function(i, v){
                        if( v.subject == id ){
                            LI = LI + "<li><input type='button' value='"+v.index+"'/></li>";    
                        }
                });

                return LI;
    });

The output is generated properly. But in the template it shows the "li" tags.

</li><li><input type='button' value='74'/></li><li><input type='button' value='75'/></li><li><input type='button' value='76'/></li><li><input type='button' value='77'/></li><li><input type='button' value='78'/></li><li><input type='button' value='79'/></li><li><input type='button' value='80'/></li><li><input type='button' value='81'/></li><li><input type='button' value='82'/></li><li><input type='button' value='83'/></li><li><input type='button' value='84'/></li><li><input type='button' value='85'/></li><li><input type='button' value='86'/></li><li><input type='button' value='87'/></li><li><input type='button' value='88'/></li><li><input type='button' value='89'/></li> 

I am calling the helper on click of button. If you have any ideas please share.

Upvotes: 0

Views: 52

Answers (2)

Sanky
Sanky

Reputation: 193

He is absolutely correct with his explanation. One more way to skip this encoding is to '#' . Try this -

{{#REQUEST_LI x}}{{/REQUEST_LI}}

[This is how default helpers like if, each are written.]

Upvotes: 0

mu is too short
mu is too short

Reputation: 434585

Handlebars HTML-encodes things that are in {{...}} by default. So if you say:

{{REQUEST_LI x}}

then your helper will produce the desired HTML as a string and then Handlebars will HTML-encode it (i.e. < becomes &lt;, ...).

There are two ways around this:

  1. The helper can return a Handlebars.SafeString: return new Handlebars.SafeString(LI) instead of return LI.
  2. You can leave it up to the template and use {{{...}}} to skip the encoding step: {{{REQUEST_LI x}}} instead of {{REQUEST_LI x}}.

I'd probably go with option 1.

A quick demo of how triple-staches and SafeStrings work: http://jsfiddle.net/ambiguous/ZN2ej/

Upvotes: 1

Related Questions