Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a handlebars #each helper with YAML front matter

I am using assemble.io to automate my frontend development, and want to use YAML front matter to create a simple nav menu.

The HTML I want to achieve is this:

<li><a href="#link1">Link1</a></li>
<li><a href="#link2">Link2</a></li>

I think the correct handlebars markup is this:

      {{#each sublinks}}
      <li><a href="#{{section}}">{{section}}</li>
      {{/each}}

But what's the correct YFM? I have started with this but know the syntax isn't correct:

---
sublinks:
  - section: link1, link2
---
like image 772
alias51 Avatar asked Dec 15 '22 06:12

alias51


2 Answers

For a template like this:

{{#each sublinks}}
<li><a href="#{{section}}">{{section}}</li>
{{/each}}

You'd want a data structure like this:

sublinks = [
    { section: 'link1' },
    { section: 'link2' },
    //...
]

and in YAML, that would look like:

sublinks:
  - section: link1
  - section: link2

You should also be able to use this YAML:

sublinks:
  - link1
  - link2

with this template:

{{#each sublinks}}
<li><a href="#{{.}}">{{.}}</li>
{{/each}}

Your YAML corresponds to a data structure like this:

sublinks = [
    { section: 'link1, link2' }
]

and that's not terribly useful unless you want to split the 'link1, link2' string using a Handlebars helper.

like image 85
mu is too short Avatar answered Dec 28 '22 07:12

mu is too short


Adding to @mu's great answer, you could also do it like this:

Given this YAML front matter:

---
sublinks:
  - href: link/to/foo
    text: Foo Text
  - href: link/to/bar
    text: Bar Text
  - href: link/to/baz
    text: Baz Text
---

Your templates would look like this:

{{#each sublinks}}
  <li><a href="#{{href}}">{{text}}</a></li>
{{/each}}

Note that the YAML specification also allows a syntax that is more JavaScript-object-like:

---
sublinks:
  - {href: link/to/foo, text: Foo Text}
  - {href: link/to/bar, text: Bar Text}
  - {href: link/to/baz, text: Baz Text}
---
like image 21
jonschlinkert Avatar answered Dec 28 '22 08:12

jonschlinkert