Add "@first" and "@last" values to "each" helper

This commit is contained in:
Dmitriy Simushev 2014-02-25 13:24:41 +00:00
parent 9d62ffd581
commit 39dd482df5
4 changed files with 23 additions and 3 deletions

View File

@ -67,7 +67,7 @@ class Context
/** /**
* @var array Special variables stack for sections. Each stack element can * @var array Special variables stack for sections. Each stack element can
* contain elements with "@index" and "@key" keys. * contain elements with "@index", "@key", "@first" and "@last" keys.
*/ */
protected $specialVariables = array(); protected $specialVariables = array();

View File

@ -126,9 +126,14 @@ class Helpers
} elseif (is_array($tmp) || $tmp instanceof \Traversable) { } elseif (is_array($tmp) || $tmp instanceof \Traversable) {
$isList = is_array($tmp) && (array_keys($tmp) == range(0, count($tmp) - 1)); $isList = is_array($tmp) && (array_keys($tmp) == range(0, count($tmp) - 1));
$index = 0; $index = 0;
$lastIndex = $isList ? (count($tmp) - 1) : false;
foreach ($tmp as $key => $var) { foreach ($tmp as $key => $var) {
$specialVariables = array('@index' => $index); $specialVariables = array(
'@index' => $index,
'@first' => ($index === 0),
'@last' => ($index === $lastIndex),
);
if (!$isList) { if (!$isList) {
$specialVariables['@key'] = $key; $specialVariables['@key'] = $key;
} }

View File

@ -293,9 +293,14 @@ class Template
if (is_array($sectionVar) || $sectionVar instanceof \Traversable) { if (is_array($sectionVar) || $sectionVar instanceof \Traversable) {
$isList = is_array($sectionVar) && (array_keys($sectionVar) == range(0, count($sectionVar) - 1)); $isList = is_array($sectionVar) && (array_keys($sectionVar) == range(0, count($sectionVar) - 1));
$index = 0; $index = 0;
$lastIndex = $isList ? (count($sectionVar) - 1) : false;
foreach ($sectionVar as $key => $d) { foreach ($sectionVar as $key => $d) {
$specialVariables = array('@index' => $index); $specialVariables = array(
'@index' => $index,
'@first' => ($index === 0),
'@last' => ($index === $lastIndex),
);
if (!$isList) { if (!$isList) {
$specialVariables['@key'] = $key; $specialVariables['@key'] = $key;
} }

View File

@ -183,6 +183,16 @@ class HandlebarsTest extends \PHPUnit_Framework_TestCase
array('data' => array('key1'=>1, 'key2'=>2,)), array('data' => array('key1'=>1, 'key2'=>2,)),
'0=>1,1=>2,' '0=>1,1=>2,'
), ),
array(
'{{#each data}}{{#if @first}}the first is {{this}}{{/if}}{{/each}}',
array('data' => array('one', 'two', 'three')),
'the first is one'
),
array(
'{{#each data}}{{#if @last}}the last is {{this}}{{/if}}{{/each}}',
array('data' => array('one', 'two', 'three')),
'the last is three'
),
array( array(
'{{#each data}}{{this}}{{else}}fail{{/each}}', '{{#each data}}{{this}}{{else}}fail{{/each}}',
array('data' => array(1, 2, 3, 4)), array('data' => array(1, 2, 3, 4)),