【问题标题】:Handlebars Access the first item and then each following (in an each loop)Handlebars 访问第一个项目,然后访问每个后续项目(在每个循环中)
【发布时间】:2015-04-01 20:54:29
【问题描述】:

我想做这样的事情:

{{object.1.name}}

{{#each object}} display name for 2, 3 4,.... and so on {{/each}}

我读到这篇文章说我可以通过编号引用:How do I access an access array item by index in handlebars?

在编程语言中,我可能会做类似的事情,或者只是有一个条件 if(据我所知,无法通过把手获得):

for(i=1; i<theEnd; i++){ display object.i} 

如果我想使用以下所有内容。

我的问题是我不知道我有多少对象,但还需要专门处理第一个。

有什么想法吗?

我错过了一个简单的解决方案吗?

【问题讨论】:

  • 也许从数组中删除第一个并在传递到车把之前自行存储?

标签: javascript html handlebars.js


【解决方案1】:

我找到了解决方案。 Jesse 的解决方案可行,但意味着在操作数据时需要将其拉入和拉出数组(效率低且麻烦)。

相反,我们可以用索引做一些事情。

这是一个例子:

$h = new Handlebars\Handlebars;

echo $h->render(
    '{{#each data}}
    {{@index}} {{#unless @last}}Not last one!{{/unless}}{{#if @last}}Last entry!{{/if}}
{{/each}}',
    array(
        'data' => ['a', 'b', 'c']
    )
);

echo "\n";

echo $h->render(
    '{{#each data}}
    {{@index}} {{#if @first}}The first!{{/if}}{{#unless @first}}Not first!{{/unless}}
{{/each}}',
    array(
        'data' => ['a', 'b', 'c']
    )
);

echo "\n";

echo $h->render(
    '{{#each data}}
    {{@index}} {{#unless @index}}The first!{{/unless}}{{#if @index}}Not first!{{/if}}
{{/each}}',
    array(
        'data' => ['a', 'b', 'c']
    )
);
the output (master) will be:

    0 Not last one!
    1 Not last one!
    2 Last entry!

    0 The first!
    1 Not first!
    2 Not first!

    0 The first!
    1 Not first!
    2 Not first!
which is what you're looking for, right? even the example in wycats/handlebars.js#483, works:

$h = new Handlebars\Handlebars;

echo $h->render(
    '
{{#each data}}
    {{@index}} 
   {{#if @last }}
       Last entry!
    {{/if}}
{{/each}}',
    array(
        'data' => ['a', 'b', 'c']
    )
);
the output:

    0 
    1 
    2 
       Last entry!

只需执行#each,然后检查是否@first,然后将其作为循环中的特殊情况进行操作。

我在这里找到了我的示例:https://github.com/XaminProject/handlebars.php/issues/52

【讨论】:

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