Example #1
0
    /**
     * Process Mustache section style
     *
     * @param Context $context current context
     * @param array   $current section node data
     *
     * @throws \RuntimeException
     * @return mixed|string
     */
    private function _mustacheStyleSection(Context $context, $current)
    {
        $sectionName = $current[Tokenizer::NAME];

        // fallback to mustache style each/with/for just if there is
        // no argument at all.
        try {
            $sectionVar = $context->get($sectionName, true);
        } catch (\InvalidArgumentException $e) {
            throw new \RuntimeException(
                $sectionName . ' is not registered as a helper'
            );
        }
        $buffer = '';
        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,
                    '@first' => ($index === 0),
                    '@last' => ($index === $lastIndex),
                );
                if (!$isList) {
                    $specialVariables['@key'] = $key;
                }
                $context->pushSpecialVariables($specialVariables);
                $context->push($d);
                $buffer .= $this->render($context);
                $context->pop();
                $context->popSpecialVariables();
                $index++;
            }
        } elseif (is_object($sectionVar)) {
            //Act like with
            $context->push($sectionVar);
            $buffer = $this->render($context);
            $context->pop();
        } elseif ($sectionVar) {
            $buffer = $this->render($context);
        }

        return $buffer;
    }