Twig icon indicating copy to clipboard operation
Twig copied to clipboard

What would you like to see as major changes that would lead to a BC break for the next major release of Twig?

Open fabpot opened this issue 1 year ago • 146 comments

We've started working on the next major Twig release. As announced last year, this new version will probably land under the Symfony mono-repository.

For the first time in Twig history, I'd like to fix the major issues that would be BC breaks and that we've never done.

This issue acts as a community wish list for things you want to see in the next major version that could lead to BC breaks (hint: like operators precedence).

Feel free to comment and vote.

fabpot avatar Dec 22 '23 07:12 fabpot

I really like the askama approach to make template type safe, and a little out of topic, it would be great if twig had an up-to-date formatter (maybe with a prettier plugin maintained by core team)

nsetyo avatar Dec 22 '23 07:12 nsetyo

I like that you started removing usage of echo and ob_* in #3950. That's a breaking change if some extension use echo instead of returning a string.

This will allow concurrent Twig renderings using fibers.

GromNaN avatar Dec 22 '23 07:12 GromNaN

I would like to see a focus on component based templating over overriding/inheritance.

For that macros need an improvement specifically the need to import them separately in every block.

Would be great to support ux html component syntax natively for creating components.

A type checker plugin (pslam/phpstan) would be nice to have as well.

aszenz avatar Dec 22 '23 08:12 aszenz

Support for step debugging via source maps would be nice.

TheCelavi avatar Dec 22 '23 08:12 TheCelavi

Plugin / Theme Structure like Shopware built around Twig. We had to built something as well and it feels bad to just copy if this could have been solved directly. And twig is already strong in multiple inheritance.

JoshuaBehrens avatar Dec 22 '23 11:12 JoshuaBehrens

Static type support for generated php to increase performance and predictable execution. I already tried to approach it but optimisation levels were commented as too breaking. So we could break it here. https://github.com/twigphp/Twig/pull/3928

JoshuaBehrens avatar Dec 22 '23 11:12 JoshuaBehrens

Still be able to use Twig without pulling a lot of more dependencies.

E.g when you merge the twig symfony bridge into the twig package and in a small project just want to get some templating, you don't get the whole dependency clutter from the framework bundle. I don't use laravel/blade because you always get so much laravel stuff with it. I just want something small that can do inheritance and autoescape. Otherwise I would just use php right away.

I see benefits in merging some code from expression language as twig has to parse expressions as well and has "just" some nodes on top.

JoshuaBehrens avatar Dec 22 '23 11:12 JoshuaBehrens

Change the null-coalescing operator to an empty- (or falsy-) coalescing operator. All the time I have a variable that is empty but not null, and I want to do variable ?? 'Something', but I can’t. And if ? : works on falsiness, then so should ??.

EDIT: I expected some 👎🏻 reactions but I'd like to hear an explanation for them

75th avatar Dec 22 '23 15:12 75th

Some type of script block to write multiple statements without typing {% %} for every line would be nice.

Something like this:

{% script %}
set counter = 0;
set color = "#33b5e5";
set list_items = [{  ... }, { ... }];

if (some_var is same as true)
    set list_items = [...list_items, { ... }];
endif
{% endscript %}

neluba avatar Dec 22 '23 15:12 neluba

Definitely two things:

Removing entirely the line tag

It is not a template syntax but a compilation syntax, as discussed there: https://github.com/twigphp/Twig/pull/353.

Rethinking the block philosophy

As of today, the block tag serves two purposes: declare a block and output a block. This not only creates confusion but also forces the compiler to make some arbitrary and non consistent decision like allowing a block definition inside a set but forbidding it inside a if (see https://github.com/twigphp/Twig/issues/3926).

I think that the block tag should be dedicated to declare a block - and should be at the root level of template - and the block and parent functions dedicated to display them.

If you're intested in discussing this, I can write a special version of Twing that implement this specification so that we can test the behaviour with embed.

Typically a big breaking change.

ericmorand avatar Dec 22 '23 17:12 ericmorand

Change the null-coalescing operator to an empty- (or falsy-) coalescing operator. All the time I have a variable that is empty but not null, and I want to do variable ?? 'Something', but I can’t. And if ? : works on falsiness, then so should ??.

EDIT: I expected some 👎🏻 reactions but I'd like to hear an explanation for them

Its called the null coalescing operator for a reason. The whole php community is moving towards more strict typing, let's not create unexpected results by changing a well known concept like ??. For your case I would implement a custom function or just make sure the data sent to the template is correct.

reinierbutot avatar Dec 22 '23 17:12 reinierbutot

Add the possibility for global macro inheritance. Import in base template and available in all inheriting templates. Maybe a globalmacro keyword?

reinierbutot avatar Dec 22 '23 17:12 reinierbutot

Its called the null coalescing operator for a reason.

It's called that because that is what it does. If it did something else, it could be called something else.

The whole php community is moving towards more strict typing,

Twig is not PHP. It is written in PHP, it compiles to PHP, but it is its own language with its own goals. (inb4 "Your idea would be an ’own goal!’”) I don't believe its goal is merely "Enable back-end OOP PHP experts to write 1:1 PHP code in fewer characters".

let's not create unexpected results

This thread is specifically about breaking changes. Anything accepted from this thread will be equally unexpected to the person who compiles an old Twig file with the new version without reading the new docs.

For your case I would implement a custom function

?? is syntactic sugar for an easily conceived but lengthily typed combination of other Twig logic. The entire point is the brevity, and making it way more useful for common cases in a language that is not striving to be as strict as PHP proper is. And frankly, even if a null-coalescing operator is more appropriate for a stricter language, it kind of sucks that the question marks in ? : and ?? mean similar but very-importantly-different things.

or just make sure the data sent to the template is correct.

Shall we deprecate the set tag, then? What about the |map filter? The Twig language could be a lot smaller if we told all its users to just make sure the data is correct before it's sent to the template's context.

Anyway, I won't say any more, this is clearly a non-starter. I don't think it should be, though. I'm full-stackish, I can write clean and pretty and strictly typed OOP PHP myself, but I don't think those same sensibilities should be uniformly applied to a template language meant to make front-end developers' lives easier.

75th avatar Dec 22 '23 17:12 75th

I agree with most of the points @75th is raising, but let me add a bit of fuel to them:

Twig is not PHP. It is written in PHP, it compiles to PHP, but it is its own language with its own goals.

This should be in the front page of every article and documentation dedicated to Twig. Twig is not "a templating language for PHP" for a good reason: the definition does not make sense. No language can be a language for another language. I'm sure that said this way, everybody would agree that it makes no sense.

Twig is a language, with compilers dedicated to be run by different runtimes (PHP, Ruby, NodeJS, browser runtimes...). And as such, it can - and must in my opinion - make its own decisions.

the question marks in ? : and ?? mean similar but very-importantly-different things.

This should definitely raise some concern: that the ternary operator is not strict but that the nullish coallescing one is is something that it not consistent and goes against @reinierbutot "The whole [...] community is moving towards more strict typing". If one is strict, the other must be strict. If one is not, the other must not be.

Shall we deprecate the set tag, then? What about the |map filter? The Twig language could be a lot smaller if we told all its users to just make sure the data is correct before it's sent to the template's context.

Absolutely correct: @reinierbutot, if your position is "just make sure the data sent to the template is correct", then why these last years have seen more and more functions and filters added to Twig that are dedicated to manipulate and generate data instead of just outputting data?

Why do the formatting filters exist? The backend knows everything required to send appropriately formatted dates or numbers or currencies or countries to the templates, so why were these formatting features added if "just make sure the data sent to the template is correct"?

Why do the date creation function exist? The backend knows how to create a date and should send dates to the templates, right?

I think we must not forget that a templating language main purpose is to process plain text. So, yeah, @reinierbutot, I agree with you that we must "make sure the data sent to the template is correct". But you have to admit that it is not the direction that Twig has been taking - and it is getting worse and worse everyday (eg the infamous cache tag that is the strict definition of something that is not in the scope of a templating language).

ericmorand avatar Dec 22 '23 18:12 ericmorand

In template inheritance, variables set outside blocks in child templates should have priority over these declared in base template https://blog.srsbiz.pl/2021/07/scope-of-set-in-twig-templates/

srsbiz avatar Dec 22 '23 19:12 srsbiz

@ericmorand

Why do the formatting filters exist? The backend knows everything required to send appropriately formatted dates or numbers or currencies or countries to the templates, so why were these formatting features added if "just make sure the data sent to the template is correct"?

As someone coming from extending applications built-upon a framework I sometimes do not have the option to change the data, that I get. "Have no option" means no services in DI, no events in event dispatcher or as in "no data returned from a controller but rendered directly". There is always the vendor patching way but I try to focus on something maintainable.

Example: when someone is giving me a doctrine entity for the template I just get a DateTimeInterface property, that could be not yet timezoned or formatted. And I think this is good. So when I have a data cache, the entity can be held in the cache independent to who renders the entity.

Another example: Sometimes data is expressed twice. So when I display a date human readable, I have often have a structured data part, that expresses the same date but in a machine readable format. So I'd rather have the date once in the template data and be able to format it whenever I need it in whatever format I need it. This is the part, that gives me flexibility in changing templates of others.

JoshuaBehrens avatar Dec 22 '23 19:12 JoshuaBehrens

@JoshuaBehrens I get your point and I agree - but it says a lot about how backend are (not) specified - and mainly driven by the frameworks instead of by the requirements - and how frontend developers are left behind even today.

My point is that if one says that "data sent to the template is correct", then it makes all the filters and data manipulators of Twig not legit.

ericmorand avatar Dec 22 '23 19:12 ericmorand

I would love the ability to statically analyze twig templates with phpstan/psalm. Twig templates are one of the remaining vulnerable parts of codebases to breaking changes and not knowing it.

jwage avatar Dec 22 '23 21:12 jwage

@ericmorand @75th thanks guys.

So you want var ?? other_var logic to be identical to var ?: other_var?

It does actually feel more like the Twig way. I'll be looking forward to using this new falseycoalescing operator 😂

reinierbutot avatar Dec 22 '23 22:12 reinierbutot

@reinierbutot, well, I don't have a PHP setup ready but even in JavaScript, the behaviour of the ternary and the nullish coallescing operators are not consistent - or maybe they are but it is not obvious to me:

console.log(null ?? 5); // 5
console.log(null ? 4 : 5); // 5
console.log('' ?? 5); // <empty string>
console.log('' ? 4 : 5); // 5

As you can see, '' is considered as truthy in the third statement, but falsy in the fourth. So maybe Twig is right, and you are too.

ericmorand avatar Dec 22 '23 23:12 ericmorand

Maybe not a BC break and even maybe discarded already, but what about allow to pass an object as context when rendering a template?

yguedidi avatar Dec 23 '23 00:12 yguedidi

So you want var ?? other_var logic to be identical to var ?: other_var?

Ohh, crap. I must confess: I didn’t realize that a ?: b was valid PHP and Twig, probably because it’s not valid JavaScript and I mistakenly wrote off the concept everywhere. I still think it’s kind of ugly to have ? mean something different in two different operators, but then I guess if you take ?: as “not a thing” and ?? as “REALLY not a thing” then it makes a certain sense.

So, request withdrawn.

(for that matter, it might have been nice to have it be ??: so you could do a ?? b : c, even though that would be useful infrequently)

75th avatar Dec 23 '23 01:12 75th

The fact that the default default value of the default filter (wow, that sounds complicated) is '' and not null cost me a lot of time in the past. I think it would meet dev's expectations more when it returns null if nothing else is specified.

- function _twig_default_filter($value, $default = '')
+ function _twig_default_filter($value, $default = null)

tjveldhuizen avatar Dec 23 '23 12:12 tjveldhuizen

Having new extension points somewhere between Parser and Lexer could facilitate Twig/LiveComponent maintenance and unlock some new features :)

smnandre avatar Dec 23 '23 12:12 smnandre

Very personal wish, but I'd love to have "private" templates (as in "not possible to override" with the multi-paths system, or extends)

smnandre avatar Dec 23 '23 12:12 smnandre

I almost forgot... those are also old wishes of mine, but i can't remember / understand why i marked them at "not doable"

if set / ifset

The equivalent of PHP if ($foo = ..)

{% ifset foo = bar|blop %}. ... {% endifset %}

Break

Any method to "exit" while in loops, but ideally also inside blocks

smnandre avatar Dec 23 '23 12:12 smnandre

Strict typing for example using === instead of same as (faster DX)

vinceAmstoutz avatar Dec 23 '23 14:12 vinceAmstoutz

I'd like to be able to combine a set and if statement.

{% if count = post.comments.count %}
  There are {{ count }} comments.
{% endif %}

instead of

{% set count = post.comments.count %}
{% if count %}
  There are {{ count }} comments.
{% endif %}

tacman avatar Dec 23 '23 16:12 tacman

I find adding properties to objects to be complicated and hard to read. I'd like to be able to add an element to an object without doing the merge, e.g. instead of

{% if options.depth is not none %}
{% set options = options|merge({'depth': currentOptions.depth - 1}) %}
{% endif %}
{# update the matchingDepth for children #}
{% if options.matchingDepth is not none and options.matchingDepth > 0 %}
{% set options = options|merge({'matchingDepth': currentOptions.matchingDepth - 1}) %}
{% endif %}

from https://github.com/KnpLabs/KnpMenu/blob/master/src/Knp/Menu/Resources/views/knp_menu.html.twig#L34C29-L41

I'd like to be able to simply set an object property.

{% set options.currentDepth = currentOptions.depth - 1 %}

It'd be even better if there were a way to combine the if statement with the set

{% set options.currentDepth = (currentOptions.depth) - 1 if  options.depth is not none %}
{% options.depth is not none ? set options.currentDepth = (currentOptions.depth) - 1 %}

Just brainstorming on the if / set, but the ability to set a single property would be really nice.

tacman avatar Dec 23 '23 16:12 tacman

I would love the ability to statically analyze twig templates with phpstan/psalm. Twig templates are one of the remaining vulnerable parts of codebases to breaking changes and not knowing it.

Clearly a must have even if it's not directly linked to twig codebase ! Extending this check to twig bridge render arguments would be perfect.

It's a bit off, but with sf router we have the same vulnerability when you change an arg name. How are you managing it ? (except using static call like myClassController::routeParams(/* here a duplicate from __invoke params except Request*/) + fqcn-based route myClassController::class maybe, i did some similar experiments around league/plates).

RobinDev avatar Dec 27 '23 08:12 RobinDev