π‘ Node `assert`β
Acting as a spinoff to #4165 Add tag to declare variable types (as I don't want to disrupt the main conversation too much π )
The idea is to introduce assertions.
I'm opening this to gather feedback and ideas. I'd like to see if there's something interesting hereβor not. :)
This could enhance static analysis, define contracts in templates, and serve as a validator during includes/rendering.
{% assert name string %}
{% assert size in ['sm', 'md', 'lg'] %}
Open to any feedback :)
Usage / syntax examples
| Langage | Code example |
|---|---|
| PHP | assert(in_array($size, ['sm', 'md'])); |
| Python | assert size in ['sm', 'md'] |
| Java | assert java.util.Arrays.asList("sm", "md").contains(size); |
| C | assert(strcmp(size, "sm") == 0 || strcmp(size, "md") == 0); |
| JavaScript | console.assert(["sm", "md"].includes(size)); |
| C++ | assert(size == "sm" || size == "md"); |
| Ruby | raise 'Assertion failed' unless ['sm', 'md'].include?(size) |
(Table made with some gpt - for representational purposes only)
When it comes to asserting variable types, that can be left over to extensions like TwigQI, once types is merged.
I do like the idea of using assert for expressions.
There's currently no way to intentionally throw an Exception of trigger a warning (aside from something silly like {{ [].foo }}).
I'd propose that the assert tag should have an optional message as part of its spec:
{% assert <expression> [message string] %}
@ruudk is working on compiling Twig templates to PHP in such a way that PHPStan can work its magic. If the assert tag gets a similar treatment, with properly typed variables, we can take a huge leap in template quality.
@ruudk is working on compiling Twig templates to PHP in such a way that PHPStan can work its magic. If the
asserttag gets a similar treatment, with properly typed variables, we can take a huge leap in template quality.
I'm curious to see how that would look like... but also if that's something we can include in the "default" Twig compilation (I suppose this is based on attributes/annotations with no runtime side-effects).
You can read more about TwigStan here: https://github.com/twigphp/Twig/discussions/4233
Now that we have the types tag, can we close this one?
Now that we have the
typestag, can we close this one?
In the end, i think this "assert" would be more related to assertions / tests than strict typing...
But I do agree we should focus on the "types" tag and see how / why it is used, the features it enables, ...
(and we can reopen here if needed later)