From 96dade342fe189f931420c5cb089af8a204d531f Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 27 Feb 2025 08:23:12 +0100 Subject: [PATCH] Improve docs on creating new tags --- doc/advanced.rst | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/doc/advanced.rst b/doc/advanced.rst index 43cdc69a8a..432892aefe 100644 --- a/doc/advanced.rst +++ b/doc/advanced.rst @@ -504,6 +504,7 @@ Now, let's see the actual code of this class:: public function parse(\Twig\Token $token) { $parser = $this->parser; + $lineno = $token->getLine(); $stream = $parser->getStream(); $name = $stream->expect(\Twig\Token::NAME_TYPE)->getValue(); @@ -511,7 +512,7 @@ Now, let's see the actual code of this class:: $value = $parser->getExpressionParser()->parseExpression(); $stream->expect(\Twig\Token::BLOCK_END_TYPE); - return new CustomSetNode($name, $value, $token->getLine()); + return new CustomSetNode($name, $value, $lineno); } public function getTag() @@ -546,6 +547,18 @@ from the token stream (``$this->parser->getStream()``): Parsing expressions is done by calling the ``parseExpression()`` like we did for the ``set`` tag. +When encountering a syntax error during parsing, throw an exception:: + + throw new SyntaxError('Some error message.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); + +For better error reporting to the user, follow these recommendations: + + * Use ``\Twig\Error\SyntaxError``; + + * **Always** pass the line number of the node and the source context; + + * End the exception message with a dot. + .. tip:: Reading the existing ``TokenParser`` classes is the best way to learn all @@ -590,7 +603,8 @@ developer generate beautiful and readable PHP code: ``\Twig\Node\ForNode`` for a usage example). * ``addDebugInfo()``: Adds the line of the original template file related to - the current node as a comment. + the current node as a comment. It's highly recommended to call this method + when implementing custom nodes. * ``indent()``: Indents the generated code (see ``\Twig\Node\BlockNode`` for a usage example). @@ -598,6 +612,10 @@ developer generate beautiful and readable PHP code: * ``outdent()``: Outdents the generated code (see ``\Twig\Node\BlockNode`` for a usage example). +For structural nodes, always call ``addDebugInfo()`` early on in the +compilation process to improve error reporting to the user in case the code +would throw an exception. + .. _creating_extensions: Creating an Extension