Skip to content

Commit

Permalink
minor #4601 Improve docs on creating new tags (fabpot)
Browse files Browse the repository at this point in the history
This PR was merged into the 3.x branch.

Discussion
----------

Improve docs on creating new tags

/cc `@smnandre`

Commits
-------

96dade3 Improve docs on creating new tags
  • Loading branch information
fabpot committed Feb 27, 2025
2 parents 4e1fa3a + 96dade3 commit 932a584
Showing 1 changed file with 20 additions and 2 deletions.
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

0 comments on commit 932a584

Please sign in to comment.