Handlebars访问第一个项目,然后访问后面的每个项目(在每个循环中)

Handlebars Access the first item and then each following (in an each loop)

本文关键字:项目 访问 循环 第一个 然后 Handlebars      更新时间:2023-09-26

我想做这样的事情:

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

我读到这篇文章,上面说我可以通过数字引用:如何通过手把中的索引访问访问数组项?

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

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

如果我想处理以下所有内容。

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

有什么想法吗?

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

我找到了一个解决方案。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,然后先检查是否为@,然后在循环中将其作为特例进行操作。

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