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

Feature/dev 1101 set new global variables from twig #13050

Merged

Conversation

brandonkelly
Copy link
Member

@brandonkelly brandonkelly commented Apr 4, 2023

Description

Adds a new _globals global Twig variable for front-end templates, set to an empty collection. All templates have access to it, and can set/retrieve values on it, providing a way for templates to store custom values in a global scope.

A new set() macro has also been added to collections, which can work as an alias of Collection::put() (key + value arguments), and it also accepts an array of key/value pairs.

{# setting values: #}
{% do _globals.set('foo', 'bar') %}
{% do _globals.set({
  foo: 'bar',
  baz: 'qux',
}) %}

{# getting values: #}
{{ _globals.foo }}
{{ _globals.get('foo') }}
{% dump globals.all() %}

Related issues

@brandonkelly brandonkelly requested a review from a team as a code owner April 4, 2023 18:39
@linear
Copy link

linear bot commented Apr 4, 2023

DEV-1101 Set new global variables from Twig templates

It should be possible to define new “global variables” from Twig templates, piggybacking on the new fallback variable support added in 4.4.

[ci skip]
@brandonkelly brandonkelly merged commit 2d79210 into 4.5 Apr 4, 2023
@brandonkelly brandonkelly deleted the feature/dev-1101-set-new-global-variables-from-twig branch April 4, 2023 20:53
@romainpoirier
Copy link

Nice add! Do you have any information about performance implications when using global variables?

I'm considering refactoring the values passed to some of my macros so that I can set them from global variables instead of parameters (which remain the same regardless of the context).

Will using a larger number of global variables negatively impact the performance?

@brandonkelly
Copy link
Member Author

@romainpoirier It’s hard to imagine it could have a negative performance impact. In theory the more you’re taking advantage of it, the less values have to be fetched multiple times, so you’d more likely see a performance improvement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants