Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable into nested Handlebars templates/partials

I have this context:

{
  path: "/some/path/to/files/",
  sections: [
    {
      title: "Title 1",
      files: [
        { name: "file1.zip" },
        { name: "file2.zip" }
      ]
    }
  ]
}

My templates and partials:

<!-- Global container template -->
<script id="container-template" type="text/x-handlebars-template">
    {{#each sections}}
        {{> sectionPartial }}
    {{/each}}
</script>

<!-- Section partial -->
<script id="section-partial" type="text/x-handlebars-template">
    <h2>{{ title }}</h2>
    <ul>
        {{#each files}}
            {{> filesPartial }}
        {{/each }}
    </ul>
</script>

<!-- Files Partial -->
<script id="files-partial" type="text/x-handlebars-template">
    <li>
        <!-- Below is where I need to use the path value -->
        <a href="{{ path }}{{ name }}>{{ name }}</a> 
    </li>
</script>

Ultimately I want to prepend the path to the href in the files-partial. But it's in a nested partial inside another partial. How can I access that value? I tried this:

...
{{> sectionPartial path=path }}
...

and

...
{{> filesPartial path=path }}
...

thinking it would pass the path value down into the partials, but it didn't. What am I missing here?

A related question, if I have a random variable declared somewhere in my JavaScript, how can I access that JavaScript variable in my templates and partials?

like image 390
Jake Wilson Avatar asked Aug 31 '25 18:08

Jake Wilson


1 Answers

You are on the right track, but the path needs to be

{{> filesPartial path=../path}}

Here is a fiddle. https://jsfiddle.net/18fjdq2e/1/

like image 74
xkcd149 Avatar answered Sep 02 '25 08:09

xkcd149