首页 > 解决方案 > 车把三个阵列在一个循环中

问题描述

我有一个看起来像这样的 Rust 结构:

struct Root{
    as: Vec<A>,
}

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

struct B {
    strings: Vec<String>,
}


struct C {
    strings: Vec<u32>,
}

我正在尝试使用 Rocket.rs 和 Handlebars 模板获得输出。

我的车把模板目前看起来像这样,但它不起作用。

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

我收到以下错误Error: Error rendering Handlebars template 'index' Error rendering "index" line 28, col 18: invalid digit found in string,这可能与@index我在 HBS 标签中使用的变量有关。

有没有其他方法我只能从两个数组中取出一个并将它们并排放置而不必改变我的结构?

标签: rusthandlebars.jsrust-rocket

解决方案


我不清楚你想要达到什么目的。A对于 Array 中的每个Object as,您希望遍历 和 的每个元素,bs看起来就像这样cs。这假设bscs具有相同的长度A

如果这是您想要的,那么我认为您的问题是您试图cs从 a 的上下文中访问 a bs。在{{#each bs}}块内,上下文是当前B对象。由于 aB没有 a cs,因此您需要提升上下文级别,以便返回A包含bs和的上下文cs。在 Handlebars 中,您可以使用路径更改上下文../,例如.

访问for each的每个索引的bs和at的简化模板是:csbsA

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

注意:我对查找和查找都使用了查找帮助程序以保持一致性。但是,由于我们在 的上下文中,我们可以简单地用 来引用它。如:bscsbs.

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

我创建了一个小提琴供您参考。


推荐阅读