Handlebars three arrays in one loop

528 views Asked by At

I have a Rust structure that looks something like this:

struct Root{
    as: Vec<A>,
}

struct A {
    bs: Vec<B>,
    cs: Vec<C>,
}

struct B {
    strings: Vec<String>,
}


struct C {
    strings: Vec<u32>,
}

and i'm trying to get output using Rocket.rs and Handlebars templating.

My handlebars template currently looks like this, but it doesn't work.

{{#each as}}
    {{#each bs}}
        <h4>{{@index}}</h4>
        <pre>{{bs.@index}}</pre>
        <pre>{{cs.@index}}</pre>
    {{/each}}
{{/each}}

I get the following error Error: Error rendering Handlebars template 'index' Error rendering "index" line 28, col 18: invalid digit found in string, which probably has to do with the @index variables I'm using in the HBS tags.

Is there any other way I could only get one item out of two arrays and place them side-by-side without having to alter my structure?

1

There are 1 answers

1
76484 On BEST ANSWER

It is not clear to me what you are trying to achieve. It looks like that for each A Object in the as Array that you would like to iterate over each element of bs and cs. This assumes that bs and cs have the same length for any A.

If this is what you want then I think your problem is that you are trying to access a cs from within the context of a bs. Within the {{#each bs}} block, the context is the current B Object. As a B does not have a cs, you need to step-up a context level so that you return to the context of the A which holds the bs and the cs. In Handlebars, you change the context using a path, like ../.

A simplified template that accesses the bs and the cs at each index of bs for each A would be:

{{#each as}}
    {{#each bs}}
        <h4>{{@index}}</h4>
        <pre>{{lookup ../bs @index}}</pre>
        <pre>{{lookup ../cs @index}}</pre>
    {{/each}}
{{/each}}

Note: I used the lookup helper for both the bs lookup and the cs lookup for consistency. However, as we are within the context of the bs, we could simply reference it with .. As in:

<pre>{{.}}</pre>
<pre>{{lookup ../cs @index}}</pre>

I have created a fiddle for your reference.