.. code-block:: jinja
- {% embed %}
- {% extends "sidebar.twig" %}
-
+ {% embed "sidebar.twig" %}
{% block content %}
Some content for the sidebar
{% endblock %}
{% extends page %}
{% block base %}
- {% embed %}
- {% extends "base_A.twig" %}
-
+ {% embed "base_A.twig" %}
{% block content1 %}
Content 1 for page 2
{% endblock %}
The goal of the ``base_a.twig`` base template being to factor out the ``Some
code``, ``Some other code``, and ``Yet some other code`` parts.
-The ``embed`` tag can be customized with the same options (``with``, ``only``,
-``ignore missing``) as the ``include`` tag:
+The ``embed`` tag takes the exact same arguments as the ``include`` tag:
.. code-block:: jinja
- {% embed with {'foo': 'bar'} %}
+ {% embed "base" with {'foo': 'bar'} %}
...
{% endembed %}
- {% embed with {'foo': 'bar'} only %}
+ {% embed "base" with {'foo': 'bar'} only %}
...
{% endembed %}
- {% embed ignore missing %}
+ {% embed "base" ignore missing %}
...
{% endembed %}
*/
public function parse(Twig_Token $token)
{
+ $stream = $this->parser->getStream();
+
+ $parent = $this->parser->getExpressionParser()->parseExpression();
+
list($variables, $only, $ignoreMissing) = $this->parseArguments();
- $module = $this->parser->parse($this->parser->getStream(), array($this, 'decideBlockEnd'), true);
+ // inject a fake parent to make the parent() function work
+ $stream->injectTokens(array(
+ new Twig_Token(Twig_Token::BLOCK_START_TYPE, '', $token->getLine()),
+ new Twig_Token(Twig_Token::NAME_TYPE, 'extends', $token->getLine()),
+ new Twig_Token(Twig_Token::STRING_TYPE, '__parent__', $token->getLine()),
+ new Twig_Token(Twig_Token::BLOCK_END_TYPE, '', $token->getLine()),
+ ));
+
+ $module = $this->parser->parse($stream, array($this, 'decideBlockEnd'), true);
+
+ // override the parent with the correct one
+ $module->setNode('parent', $parent);
+
$this->parser->embedTemplate($module);
- $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
+ $stream->expect(Twig_Token::BLOCK_END_TYPE);
return new Twig_Node_Embed($module->getAttribute('filename'), $module->getAttribute('index'), $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag());
}
return implode("\n", $this->tokens);
}
+ public function injectTokens(array $tokens)
+ {
+ $this->tokens = array_merge(array_slice($this->tokens, 0, $this->current), $tokens, array_slice($this->tokens, $this->current));
+ }
+
/**
* Sets the pointer to the next token and returns the old one.
*