With Twig I am using {% include %}
a lot. I need to attach ignore missing
to every include, since I do not want to run into an Exception when a file is not found. This bloats the template code a lot and I am looking for an option to attach ignore default
to all includes by default without repeating it with every include call. I am looking for an equivalent of php's include in Twig since Twig's own include behaves like php's require.
How can I include templates in Twig without having Exceptions thrown when a file is not found and without adding ignore missing
to every single include?
I was looking for a config in Twig but did not find an option.
by over-riding built-in include
class TokenParser_Include extends Twig_TokenParser
{
public function parse(Twig_Token $token)
{
$expr = $this->parser->getExpressionParser()->parseExpression();
list($variables, $only, $ignoreMissing) = $this->parseArguments();
return new Twig_Node_Include($expr, $variables, $only, $ignoreMissing = true, $token->getLine(), $this->getTag());
}
protected function parseArguments()
{
$stream = $this->parser->getStream();
$ignoreMissing = false;
if ($stream->nextIf(Twig_Token::NAME_TYPE, 'ignore')) {
$stream->expect(Twig_Token::NAME_TYPE, 'missing');
$ignoreMissing = true;
}
$variables = null;
if ($stream->nextIf(Twig_Token::NAME_TYPE, 'with')) {
$variables = $this->parser->getExpressionParser()->parseExpression();
}
$only = false;
if ($stream->nextIf(Twig_Token::NAME_TYPE, 'only')) {
$only = true;
}
$stream->expect(Twig_Token::BLOCK_END_TYPE);
return array($variables, $only, $ignoreMissing);
}
public function getTag()
{
return 'include';
}
}
$twig->addTokenParser(new TokenParser_Include());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.