11ty / eleventy-plugin-template-languages

Official template syntax plugins for Eleventy
MIT License
2 stars 1 forks source link

Handlebars each helper and collections urls throws error #11

Open scurker opened 4 years ago

scurker commented 4 years ago

Describe the bug

Using handlebars' built in #each helper and a collection's url can throw a TypeError: url.indexOf is not a function.

To Reproduce

Display a collection of items with handlebars #each:

<ul class="posts">
{{~#each collections.posts}}
  <li><a href="{{url}}">{{data.title}}</a></li>
{{~/each}}
</ul>

Expected behavior

No error.

Environment:

Additional context

What I think is happening is that handlebars is remapping object keys inside of the helper, so {{url}} inside of #each actually looks something like:

{
  name: 'url',
  hash: {},
  data: {
    root: {
      metadata: [Object],
      pkg: [Object],
      layout: 'home',
      page: [Object],
      collections: [Object],
      content: '',
      layoutContent: '',
      _layoutContent: ''
    },
    _parent: { root: [Object] },
    key: 0,
    index: 0,
    first: true,
    last: false
  },
  loc: { start: { line: 4, column: 15 }, end: { line: 4, column: 22 } }
}

...which when passed through 11ty's url filter does not have indexOf.

There's a simple workaround for this though by referencing the original object with this.url instead:

<ul class="posts">
{{~#each collections.posts}}
  <li><a href="{{this.url}}">{{data.title}}</a></li>
{{~/each}}
</ul>

Alternatively, naming the iterated value should work as well:

<ul class="posts">
{{~#each collections.posts as |post|}}
  <li><a href="{{post.url}}">{{post.data.title}}</a></li>
{{~/each}}
</ul>

Perhaps this method should be documented for handlebars?

ThePeach commented 4 years ago

@scurker thanks for detailing the problem as I stumbled the same issue as you describe here and wasn't able to debug it. using this.url worked the best, since I'm using several partials within the each loop, naming the iterator would cause me some problems.

I'd also agree, perhaps have a note/hint in the documentation would be good!