【问题标题】:Spacebars rendering according to index空格键根据索引渲染
【发布时间】:2017-05-19 07:12:53
【问题描述】:

我需要在索引模数为0时打开一行,为1时关闭它,类似于这个想法:

{{each posts}}
    {{#if @index%2==0}}
         <div class="row">
    {{/if}}
             <div class="col-lg-6">HELLO</div>
    {{#if @index%2==1}}
         </div>
    {{/if}}
{{/each}}

当然,这个代码/想法不能编译。我怎样才能实现它?

更新对不起,我可能解释得不好。我想做的是类似于此 PHP 代码但使用流星。 (更改了一些数字以便更好地理解)。

for($i = 0; $i<count(array); $i++):
    if($i%4 == 0):
        echo '<div class="row">';
    endif;
        echo '<div class="col-lg-3">HELLO</div>';
    if($i%4==3 || $i == count(array) -1):
        echo '</div>';
    endif;
endfor;

我有一个带有帮助器的解决方案,它返回一个二维数组,还有另一种方法。

【问题讨论】:

    标签: meteor meteor-blaze spacebars


    【解决方案1】:

    您可以获取索引,然后将其传递给助手来执行您的逻辑。

    {{#each posts}}
        {{#if isEven @index}}
             <div class="row">
        {{/if}}
                 <div class="col-lg-6">HELLO</div>
        {{#if isOdd @index}}
             </div>
        {{/if}}
    {{/each}}
    
    
    Template.foo.helpers({
        isEven(index) {
            return (index % 2 == 0);
        },
        isOdd(index) {
            return (index % 2 == 1);
        }
    });
    

    编辑:

    顺便说一句,你的 if 逻辑在匹配 div 时看起来是错误的。我想你的意思更像是这样的:

    {{#each posts}}
        {{#if isEven @index}}
             <div class="row">
        {{else}}
             <div class="col-lg-6">HELLO
        {{/if}}
             </div>
    {{/each}}
    

    编辑 2:

    如果 Blaze 对 div 的格式感到困惑,也许可以像这样去混淆它。它也更容易阅读:

    {{#each posts}}
        {{#if isEven @index}}
             <div class="row">
             </div>
        {{else}}
             <div class="col-lg-6">HELLO
             </div>
        {{/if}}
    {{/each}}
    

    【讨论】:

    • 由于同样的问题,此代码无法正常工作。当else 语句开始时,编译器说缺少一个结束 div。
    【解决方案2】:

    如果你无论如何都想在中间创建元素,我会做这样的事情

    {{#each posts}}
        <div class="{{#if isEven @index}}row{{/if}}">
            <div class="col-lg-6">HELLO</div>
        </div>
    {{/each}}
    

    其中(类似于@zim 建议)isEven 将是一个模板助手,将索引作为其参数

    Template.hello.helpers({
        isEven(index) {
            return index % 2 === 0;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      相关资源
      最近更新 更多