Add {{else}} support to if

This commit is contained in:
fzerorubigd 2012-11-17 15:52:51 +03:30
parent 600215d648
commit ec6761fde4
2 changed files with 54 additions and 9 deletions

View File

@ -70,14 +70,13 @@ class Handlebars_Helpers
'if',
function ($template, $context, $args, $source) {
$tmp = $context->get($args);
$parts = explode('{{else}}', $source, 2);
$buffer = '';
if ($tmp) {
$buffer = $template->getEngine()->render($parts[0], $context);
$buffer = $template->render($context, 'else');
$template->discard($context);
} else {
if (isset($parts[1])) {
$buffer = $template->getEngine()->render($parts[1], $context);
}
$template->discard($context, 'else');
$buffer = $template->render($context);
}
return $buffer;
}
@ -255,4 +254,4 @@ class Handlebars_Helpers
return empty($this->helpers);
}
}
}

View File

@ -92,11 +92,12 @@ class Handlebars_Template
/**
* Render top tree
*
* @param mixed $context current context
* @param mixed $context current context
* @param string $waitFor return on this string
*
* @return string
*/
public function render($context)
public function render($context, $waitFor = false)
{
if (!$context instanceof Handlebars_Context) {
$context = new Handlebars_Context($context);
@ -108,6 +109,17 @@ class Handlebars_Template
while (array_key_exists($index, $tree)) {
$current = $tree[$index];
$index++;
//if the section is exactly like waitFor
if (is_string($waitFor)
&& $current[Handlebars_Tokenizer::TYPE] == Handlebars_Tokenizer::T_ESCAPED
&& $current[Handlebars_Tokenizer::NAME] === $waitFor
) {
//Ok break here, the helper should be aware of this.
$newStack = array_pop($this->_stack);
$newStack[0] = $index;
array_push($this->_stack, $newStack);
break;
}
switch ($current[Handlebars_Tokenizer::TYPE]) {
case Handlebars_Tokenizer::T_SECTION :
$newStack = isset($current[Handlebars_Tokenizer::NODES]) ? $current[Handlebars_Tokenizer::NODES] : array();
@ -138,6 +150,40 @@ class Handlebars_Template
}
return $buffer;
}
/**
* Discard top tree
*
* @param mixed $context current context
* @param string $waitFor return on this string
*
* @return string
*/
public function discard($context, $waitFor = false)
{
if (!$context instanceof Handlebars_Context) {
$context = new Handlebars_Context($context);
}
$topTree = end($this->_stack); //This method never pop a value from stack
list($index ,$tree) = $topTree;
while (array_key_exists($index, $tree)) {
$current = $tree[$index];
$index++;
//if the section is exactly like waitFor
if (is_string($waitFor)
&& $current[Handlebars_Tokenizer::TYPE] == Handlebars_Tokenizer::T_ESCAPED
&& $current[Handlebars_Tokenizer::NAME] === $waitFor
) {
//Ok break here, the helper should be aware of this.
$newStack = array_pop($this->_stack);
$newStack[0] = $index;
array_push($this->_stack, $newStack);
break;
}
}
return '';
}
/**
* Process section nodes
@ -231,4 +277,4 @@ class Handlebars_Template
}
}
}