diff --git a/CHANGELOG b/CHANGELOG index 58336cef839..86f696fc422 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,6 @@ # 3.13.0 (2024-XX-XX) - * n/a + * Add the `types` tag (experimental) # 3.12.0 (2024-08-29) @@ -31,7 +31,6 @@ * Bump minimum PHP version to 8.0 * Fix integration tests when a test has more than one data/expect section and deprecations * Add the `enum_cases` function - * Add the `types` tag # 3.11.0 (2024-08-08) diff --git a/doc/tags/types.rst b/doc/tags/types.rst index f055bb23b74..a884ae400f6 100644 --- a/doc/tags/types.rst +++ b/doc/tags/types.rst @@ -1,11 +1,14 @@ ``types`` ========= -The ``types`` tag declares the types for template variables. +.. versionadded:: 3.13 + The ``types`` tag was added in Twig 3.13. This tag is **experimental** and can change based on usage and feedback. + +The ``types`` tag declares the types of template variables. To do this, specify a :ref:`mapping ` of names to their types as strings. -Here is how you declare that variable ``foo`` is a boolean, while ``bar`` is an integer (see note below): +Here is how to declare that ``foo`` is a boolean, while ``bar`` is an integer (see note below): .. code-block:: twig @@ -14,7 +17,7 @@ Here is how you declare that variable ``foo`` is a boolean, while ``bar`` is an bar: 'int', } %} -You can declare variables as optional by adding the '?' suffix: +You can declare variables as optional by adding the ``?`` suffix: .. code-block:: twig @@ -30,7 +33,7 @@ and/or required variables. While Twig itself does not validate variables or thei to do this. Additionally, :ref:`Twig extensions ` can analyze these tags to perform compile-time and -runtime analysis of templates in order to increase code quality. +runtime analysis of templates. .. note:: diff --git a/src/TokenParser/TypesTokenParser.php b/src/TokenParser/TypesTokenParser.php index 6a1cbfd0008..b579fd0c04e 100644 --- a/src/TokenParser/TypesTokenParser.php +++ b/src/TokenParser/TypesTokenParser.php @@ -39,8 +39,9 @@ public function parse(Token $token): Node } /** - * @throws SyntaxError * @return array + * + * @throws SyntaxError */ private function parseSimpleMappingExpression(TokenStream $stream): array { @@ -63,12 +64,12 @@ private function parseSimpleMappingExpression(TokenStream $stream): array $nameToken = $stream->expect(Token::NAME_TYPE); $isOptional = $stream->nextIf(Token::PUNCTUATION_TYPE, '?') !== null; - $stream->expect(Token::PUNCTUATION_TYPE, ':', 'A name must be followed by a colon (:)'); + $stream->expect(Token::PUNCTUATION_TYPE, ':', 'A type name must be followed by a colon (:)'); $valueToken = $stream->expect(Token::STRING_TYPE); - + $types[$nameToken->getValue()] = [ - 'type' => $valueToken->getValue(), + 'type' => $valueToken->getValue(), 'optional' => $isOptional, ]; }