Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve docs on creating new tags #4601

Merged
merged 1 commit into from
Feb 27, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions doc/advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -504,14 +504,15 @@ 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();
$stream->expect(\Twig\Token::OPERATOR_TYPE, '=');
$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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -590,14 +603,19 @@ 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).

* ``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
Expand Down