Add `enum_cases` function
May fix #3681.
Allows:
{% for enum in enum_cases('App\\MyBackedEnum') %}
{{ enum.value }}
{% endfor %}
Use case:
We need to display supported locales for a language switcher in the menu.
The block is included in a header template which is included in the base. It is cumbersome to pass Locale::cases() in the context from all controllers rendering a template that inherits from the base, or to cascade the variable from template to template.
Simplified implementation:
enum Locale: string
{
case EN = 'en';
case FR = 'fr';
public function flag(): string
{
return match ($this) {
self::EN => '🇬🇧',
self::FR => '🇫🇷',
};
}
}
{% for locale in enum_cases('App\\Locale') %}
<option value="{{ locale.value }}"{% if locale.value == app.locale %} selected{% endif %}>
{{ locale.flag }}
</option>
{% endfor %}
I've updated the description to show a basic use case.
Any news @HeahDude?
for reference, I implemented a similar function at Incenteev, with a specificity: I'm using a custom node type to perform a special compilation when the argument is a string literal:
- I validate that the argument is a valid enum class at compile time (which conveniently helps when you forget to escape backslashes and end up not having them in the actual string)
- I compile the code directly to a called to
MyEnum::cases()without the wrapper function, avoiding to repeat the enum validation at runtime.
Do you want me to submit my implementation as a PR ?
And I'm wondering whether it should be in a dedicated extension or in CoreExtension.
@stof It would be great if you could submit a PR. Having it in CoreExtension sounds good to me.