Skip to content

Instantly share code, notes, and snippets.

@Cifro
Created July 3, 2010 15:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cifro/462628 to your computer and use it in GitHub Desktop.
Save Cifro/462628 to your computer and use it in GitHub Desktop.
Static class for additional Nette Latte Macros with first macro {each}{eachelse}{/each}
<?php
namespace Nette\Templates;
use Nette\Object;
use Nette\String;
/**
* Another Latte Macros
*
* @author Cifro
* @license MIT
*/
class AnotherLatteMacros extends Object
{
public function __construct() {
throw new \InvalidStateException("Static class.");
}
public static function register() {
LatteMacros::$defaultMacros['each'] = '<?php %Nette\Templates\AnotherLatteMacros::macroEach% ?>';
LatteMacros::$defaultMacros['eachelse'] = '<?php endforeach; array_pop($_cb->its); $iterator = end($_cb->its); else: ?>';
LatteMacros::$defaultMacros['/each'] = '<?php endif ?>';
// \Nette\Templates\FormMacros::register(); // http://gist.github.com/347052
}
public static function macroEach($content)
{
$token = LatteFilter::fetchToken($content);
$modifiers = String::trim(LatteFilter::formatString($content), '"');
$code = "if($token === null) $token = array(); \$___iterator = new SmartCachingIterator($token);";
$code .= ' if($___iterator->count() > 0): foreach($iterator = $_cb->its[] = $___iterator ' . $modifiers . '):';
return $code;
}
}
<?php
// blabla...
Nette\Templates\AnotherLatteMacros::register();
// blabla...
{each $someArray as $key => $value}
<p>
{if $iterator->isFirst()}
First item:
{/if}
{if $iterator->isLast()}
Last item:
{/if}
{$key} => {$value}
</p>
{eachelse}
<p>Empty.</p>
{/each}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment