Search code examples
yamlhandlebars.jsassemble

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
---

Solution

  • 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.