EzDevInfo.com

handlebars.js

How to get index in Handlebars each helper?

I'm using Handlebars for templating in my project. Is there a way to get the index of the current iteration of an "each" helper in Handlebars?

<tbody>
     {{#each item}}
         <tr>
            <td><!--HOW TO GET ARRAY INDEX HERE?--></td>
            <td>{{this.key}}</td>
            <td>{{this.value}}</td>
         </tr>
     {{/each}}
</tbody>

Source: (StackOverflow)

Show property which includes html tags

I've an ember property which includes html tags (<br />, <strong>, <p>, <span>, and similar stuff).

How can i tell ember not to escape this text? Is there any default Handlebars helper from ember, or need I to write my own?


Source: (StackOverflow)

Advertisements

conditional on last item in array using handlebars.js template

I am leveraging handlebars.js for my templating engine and am looking to make a conditional segment display only if it is the last item in array contained in the templates configuration object.

{
  columns: [{<obj>},{<obj>},{<obj>},{<obj>},{<obj>}]
}

I've already pulled in a helper to do some equality/greater/less-than comparisons and have had success identifying the initial item this way but have had no luck accessing my target array's length.

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {...})

"{{#each_with_index columns}}"+
"<div class='{{#equal index 0}} first{{/equal}}{{#equal index ../columns.length()}} last{{/equal}}'>"+
"</div>"+
"{{/each_with_index}}"

Does anyone know a shortcut, different approach, and some handlebars goodness that will keep me from having to tear into the handlebars.js engine to determine best course?


Source: (StackOverflow)

Handlebar js - iterating over for basic loop

I'm new to handlebar and just started using it. Most of the examples are based on iterating over an object. I wanted to know how to use handlebars in basic for loop.

Example.

for(i=0 ; i<100 ; i++) {
   create li's with i as the value
}

How can this be achieved ?


Source: (StackOverflow)

The context of "this" in Meteor template event handlers (using Handlebars for templating)

A quick question on the context of the event handlers for templates in Meteor (with Handlebars).

  • In the section of Documentation on template instances (http://docs.meteor.com/#template_inst) it is mentioned that "Template instance objects are found as the value of this in the created, rendered, and destroyed template callbacks and as an argument to event handlers"
  • In the Templates section (http://docs.meteor.com/#templates) it says "Finally, you can use an events declaration on a template function to set up a table of event handlers. The format is documented at Event Maps. The this argument to the event handler will be the data context of the element that triggered the event."

Well, this is only partially true. Let's use an example from the docs:

<template name="scores">
  {{#each player}}
    {{> playerScore}}
  {{/each}}
</template>

<template name="playerScore">
  <div>{{name}}: {{score}}
    <span class="givePoints">Give points</span>
  </div>
</template
Template.playerScore.events({
  'click .givePoints': function () {
    Users.update({_id: this._id}, {$inc: {score: 2}});
  });

Here the "this" context of the 'click .givePoints' event handler is indeed the template instance of playerScore. Let's modify the html:

<template name="scores">
  <span class="click-me">Y U NO click me?<span>
  {{#each player}}
    {{> playerScore}}
  {{/each}}
</template>

<template name="playerScore">
  <div>{{name}}: {{score}}
    <span class="givePoints">Give points</span>
  </div>
</template>

... and add an event handler for .click-me on the scores template:

Template.scores.events({
  'click .click-me': function () {
    console.log(this);
  }
});

Now, if you click the span, what do you get logged? The Window object! What did I expect to get? The template object! Or maybe the data context, but it's neither. However, inside the callbacks (e.g. Template.scores.rendered = function(){ ... }) the context of "this" is always the template instance.

I guess my real question would be: is this something to do with

  • a bug in Handlebars, Meteor or somewhere in between?
  • slightly incomplete documentation on the templates?
  • me completely misinterpreting the docs or not understanding something fundamental about Meteor or Handlebars?

Thanks!


Source: (StackOverflow)

How to find Array length inside the Handlebar templates?

I have a Handlebar template which is rendered using a json object. In this json I amm sending an array. like this:

var json = {
               "array":["abc","def","ghi","jkl"] 
}

Now in my template I want to find the length of this array something like:

{{#each item}}
   {{ array.length }}
{{/each}}

Couldn't find in the Handlebar documentation.


Source: (StackOverflow)

What is the difference between handlebar.js and handlebar.runtime.js?

I found that handlebar.runtime.js has no compile method. So I downloaded not the right version to just use the template engine.

But what is the handlebar.runtime.js is for?

It would be nicer that Download: runtime-1.0.0 would be more unnoticeable on the download page?


Source: (StackOverflow)

Handlebars partial vs. render vs. template

The Fire Up Ember.js screencast uses partial, template, render to render templates within templates, but I'm still not sure I know which one to use when.

In the same screencast the partial is explained as using the context and all data relative to the current controller, while render uses the the specified controller's matching template, context etc:

Fire Up Ember.js: partial versus Fire Up Ember.js

Can someone please clarify the differences between partial, template, render and when (examples) to use which?


Source: (StackOverflow)

How to use multiple parameters in a handlebar helper with meteor?

I am trying to create a custom helper using Meteor. Following to the doc here: https://github.com/meteor/meteor/wiki/Handlebars

I have tried to define my helper as follows:

Template.myTemplate.testHelper = function(foo, bar, options) {
    console.log(foo);
    console.log(bar);
}

My template looks like:

<template name="myTemplate">
    {{#testHelper "value1" "value2"}}
    {{/testHelper}}
</template>

Looking at my console output, I expected to see 2 lines of output:

value1
value2

However my console looks like:

value1
function (data) {
    // don't create spurious annotations when data is same
    // as before (or when transitioning between e.g. `window` and
    // `undefined`)
    if ((data || Handlebars._defaultThis) ===
        (old_data || Handlebars._defaultThis))
      return fn(data);
    else
      return Spark.setDataContext(data, fn(data));
  } 

Note, I am completely new to meteor, and to handlebars. I think I would be much happier using underscore, but the documentation for meteor glances over underscore almost entirely. Am I doing something wrong defining my helper function? It seems that it is not seeing the second parameter "bar", and instead interpreting that as the options. (Note: if I console.log(options) it returns 'undefined').

Meteor version 0.4.0 (8f4045c1b9)


Source: (StackOverflow)

Check for a value equals to in Ember Handlebar If block helper

How do we check for a value equality in ember.js's If-block helper?

{{#if person=="John"}}

How do we perform above in handlebars?


Source: (StackOverflow)

How to make i18n with Handlebars.js (mustache templates)?

I'm currently using Handlebars.js (associated with Backbone and jQuery) to make a web app almost totally client side rendered, and I'm having issues with the internationalisation of this app.

How can I make this work?

Are there any plugins?


Source: (StackOverflow)

Handlebars Template rendering template as text

I created a helper in Handlebars to help with logic, but my template parses the returned html as text rather than html.

I have a quiz results page that is rendered after the quiz is completed:

  <script id="quiz-result" type="text/x-handlebars-template">
        {{#each rounds}}
          {{round_end_result}}
        {{/each}}
        <div class="clear"></div>
  </script>

For each of the rounds, I use a helper to determine which template to render a round's result:

  Handlebars.registerHelper("round_end_result", function() {
    if (this.correct) {
      var source = '';
      if (this.guess == this.correct) {
        console.log("correct guess");
        var source = $("#round-end-correct").html();
      } else {
        var source = $("#round-end-wrong").html();
      }
      var template = Handlebars.compile(source);
      var context = this;
      var html = template(context);
      console.log(html);
      return html;
    } else {
      console.log("tie");
    }
  });

Here is a template that describes a correct round (let's take say it rendered the #round-end-correct template):

  <script id="round-end-correct" type="text/x-handlebars-template">
        <div></div>
  </script>

Here is what gets rendered:

<div></div>

Not as HTML, but as text. How do I get it to actually render the HTML as HTML, rather than text?


Source: (StackOverflow)

Meteor, how to access to a helper from another helper?

I have a helper like

Template.user_profile.helpers({
  user:function() {
     return Meteor.users.find({'profile.front_name':Session.get('slug')}).fetch()[0];
  }
});

I want to add a helper to the collection which could access the user helper and compare its _id with the current user _id, to tell whether the user is visiting its own profile. I'm using something pretty ugly:

Template.user_profile._tmpl_data.helpers.user()

The final code:

Template.user_profile.helpers({
  user:function() {
     return Meteor.users.find({'profile.front_name':Session.get('userId')}).fetch()[0];
  },
  isCurrentUser: function() {
    return Template.user_profile._tmpl_data.helpers.user()._id === Meteor.userId();
  }
});

Is there any better way to access another helper?


Source: (StackOverflow)

Access a variable outside the scope of a Handlebars.js each loop

I have a handlebars.js template, just like this:

{{externalValue}}

<select name="test">
    {{#each myCollection}}
       <option value="{{id}}">{{title}} {{externalValue}}</option>
    {{/each}}
</select>

And this is the generated output:

myExternalValue

<select name="test">
       <option value="1">First element </option>
       <option value="2">Second element </option>
       <option value="3">Third element </option>
</select>

As expected, I can access the id and title fields of every element of myCollection to generate my select. And outside the select, my externalValue variable is correctly printed ("myExternalValue").

Unfortunately, in options' texts, externalValue value is never printed out.

My question is: how can I access a variable outside the scope of the handlebars.js each from within the loop?

As always, thanks in advance.


Source: (StackOverflow)

handlebars - is it possible to access parent context in a partial?

I've got a handlebar template that loads a partial for a sub-element.

I would need to access a variable from the parent context in the calling template, from within the partial. .. doesn't seem to resolve to anything inside the partial.

Simplified code goes like this:

the template

    {{#each items}} 
        {{> item-template}}
    {{/each}}

the partial

    value is {{value}}

(obviously the real code is more complicated but it's the same principle, within the partial .. appears to be undefined.)


To show it's undefined, I've used a very simple helper whatis like this:

Handlebars.registerHelper('whatis', function(param) {
    console.log(param);
});

and updated the above code to this:

updated template

    {{#each items}} 
        {{whatis ..}}  <-- Console shows the correct parent context
        {{> item-template}}
    {{/each}}

updated partial

    {{whatis ..}}  <-- Console shows "undefined"
    value is {{value}}

Is there a way to go around that issue? Am I missing something?

EDIT: There's an open issue relating to this question on handlebars' github project


Source: (StackOverflow)