Handlebars EACH iterator error

Go To StackoverFlow.com

0

I'm new to Handlebars and while I found a workaround, I'm wondering why one registered helper works and one doesn't. The example that doesn't work is an example from the HB docs.

HTML:

<ul class="global-nav clearfix">
  {{#each data}}
 <li><a href="{{href}}">{{text}}</a></li>
 {{/each}}
</ul>
...
<ul class="content-nav clearfix">
  {{#each data}}
  <li><a href="{{href}}">{{text}}</a></li>
  {{/each}}
</ul>

Data:

var nav = [
  {
    name: 'global',
    selector: $('.global-nav'),
    data: [
      {
        text: 'Page 1',
        href: 'page1.html'
      }, {
        text: 'Page 2',
        href: 'page2.html'
      }
    ],

    name: 'content',
    selector: $('.content-nav'),
    data: [
      {
        text: 'Section 1',
        href: '#section1'
      }, {
        text: 'Section 2',
        href: '#section2'
      }
    ]
  }
];

Compiler:

$.each(nav, function() {
  var obj = this,
      src = obj.selector.html(),
      template = Handlebars.compile(src),
      html = template(obj.data);

  obj.selector.html(html);
});

HB Helper (does not work - context is undefined):

Handlebars.registerHelper('each', function(context, options) {
  var ret = "";

  for(var i=0, j=context.length; i<j; i++) {
    ret = ret + options.fn(context[i]);
  }

  return ret;
});

HB Helper (does work using this instead of context):

Handlebars.registerHelper('each', function(context, options) {
  var ret = "";

  for(var i=0, j=this.length; i<j; i++) {
    ret = ret + options.fn(this[i]);
  }

  return ret;
});

Any helps is appreciated.

2012-04-03 19:26
by CoryDorning


0

Before looking at the rest of the JS, can I point out that the JSON looks wrong.

Name, selector and data are overwritten the second time they occur in your JSON. If this is just because of some bits being omitted when pasting to SO, then do ignore me ;o)

But if that is the real JSON, then it needs changing before looking at any functional stuff

<script>
var nav = [
{
  name: 'global',
  selector: $('.global-nav'),
  data: [
    {
      text: 'Page 1',
      href: 'page1.html'
    }, {
      text: 'Page 2',
      href: 'page2.html'
    }
  ]
}, // this line 
{  // and this line added
  name: 'content',
  selector: $('.content-nav'),
  data: [
    {
      text: 'Section 1',
      href: '#section1'
    }, {
      text: 'Section 2',
      href: '#section2'
    }
  ]
}
];
</script>
2012-04-11 09:33
by joevallender
Ads