Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Add `enum_cases` function

Open HeahDude opened this issue 2 years ago • 1 comments

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 %}

HeahDude avatar Aug 22 '23 09:08 HeahDude

I've updated the description to show a basic use case.

HeahDude avatar Aug 24 '23 08:08 HeahDude

Any news @HeahDude?

fabpot avatar Aug 04 '24 14:08 fabpot

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 ?

stof avatar Aug 06 '24 09:08 stof

And I'm wondering whether it should be in a dedicated extension or in CoreExtension.

stof avatar Aug 06 '24 10:08 stof

@stof It would be great if you could submit a PR. Having it in CoreExtension sounds good to me.

fabpot avatar Aug 06 '24 20:08 fabpot