0

I want to do something like this:

{{object.1.name}}

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

I read this which says I can reference by number: How do I access an access array item by index in handlebars?

in a programming language I might do something like or simply have a conditional if (not available to my knowledge through handlebars):

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

If i wanted to work with all of the following.

My problem is that I do not know how many objects I have but also need to handle the first specially.

Any ideas?

Did I miss an easy solution?

Community
  • 1
  • 1
Tai
  • 1,206
  • 5
  • 23
  • 48

1 Answers1

2

I found a solution. Jesse's solution would work but would mean that as the data is manipulated it would need to be pulled in and out of the array (inefficient and a hassle).

Instead we can do something with index.

Here is an example:

$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!

simply do an #each and then check if @first and then manipulate it as a special case in your loop.

I found my example here: https://github.com/XaminProject/handlebars.php/issues/52

Tai
  • 1,206
  • 5
  • 23
  • 48