From 39dd482df5777d2a2bebc0fe8cf21252695b298e Mon Sep 17 00:00:00 2001 From: Dmitriy Simushev Date: Tue, 25 Feb 2014 13:24:41 +0000 Subject: [PATCH] Add "@first" and "@last" values to "each" helper --- src/Handlebars/Context.php | 2 +- src/Handlebars/Helpers.php | 7 ++++++- src/Handlebars/Template.php | 7 ++++++- tests/Xamin/HandlebarsTest.php | 10 ++++++++++ 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/Handlebars/Context.php b/src/Handlebars/Context.php index 2cbbfc6..cefff55 100644 --- a/src/Handlebars/Context.php +++ b/src/Handlebars/Context.php @@ -67,7 +67,7 @@ class Context /** * @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(); diff --git a/src/Handlebars/Helpers.php b/src/Handlebars/Helpers.php index 288de00..625e785 100644 --- a/src/Handlebars/Helpers.php +++ b/src/Handlebars/Helpers.php @@ -126,9 +126,14 @@ class Helpers } elseif (is_array($tmp) || $tmp instanceof \Traversable) { $isList = is_array($tmp) && (array_keys($tmp) == range(0, count($tmp) - 1)); $index = 0; + $lastIndex = $isList ? (count($tmp) - 1) : false; foreach ($tmp as $key => $var) { - $specialVariables = array('@index' => $index); + $specialVariables = array( + '@index' => $index, + '@first' => ($index === 0), + '@last' => ($index === $lastIndex), + ); if (!$isList) { $specialVariables['@key'] = $key; } diff --git a/src/Handlebars/Template.php b/src/Handlebars/Template.php index c53bb28..cfbea32 100644 --- a/src/Handlebars/Template.php +++ b/src/Handlebars/Template.php @@ -293,9 +293,14 @@ class Template if (is_array($sectionVar) || $sectionVar instanceof \Traversable) { $isList = is_array($sectionVar) && (array_keys($sectionVar) == range(0, count($sectionVar) - 1)); $index = 0; + $lastIndex = $isList ? (count($sectionVar) - 1) : false; foreach ($sectionVar as $key => $d) { - $specialVariables = array('@index' => $index); + $specialVariables = array( + '@index' => $index, + '@first' => ($index === 0), + '@last' => ($index === $lastIndex), + ); if (!$isList) { $specialVariables['@key'] = $key; } diff --git a/tests/Xamin/HandlebarsTest.php b/tests/Xamin/HandlebarsTest.php index 9dd22ed..c063172 100644 --- a/tests/Xamin/HandlebarsTest.php +++ b/tests/Xamin/HandlebarsTest.php @@ -183,6 +183,16 @@ class HandlebarsTest extends \PHPUnit_Framework_TestCase array('data' => array('key1'=>1, 'key2'=>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( '{{#each data}}{{this}}{{else}}fail{{/each}}', array('data' => array(1, 2, 3, 4)),