Yes, that's something we need often! I did it for some apps in another way, by adding a custom filter |filter (for PHP: array_filter()) in combination with |keys|join(' '), but definitely a built-in function would be quite useful.
I'm guessing something like this:
<div class="{{ class_names({
'class1': condition1,
'class2': condition2,
'class3': condition3,
}) }}">
{# ... #}
</div>
I like this proposal ... but I'm not a big fan of the proposed function names. Although Twig is for front-end people, it's used by lots of backend people, so "classes" sounds like programming classes, not CSS classes.
Also, front-end people use classes in JavaScript ... so it may be confusing to them too.
What about calling it css_class() ? There's no need to use plural because in Twig we always use singular even when the usage is plural (e.g. include() and not includes())
Or maybe something more generic, like join (maybe confusing with the existing filter with same name?) or conditional_join, with explicit separator?
<div class="{{ conditional_join(' ', 'a-class', 'another-class', {
'errored': object.errored,
'finished': object.finished,
'pending': object.pending,
}) }}">
</div>
conditional_join(separator, ...args)
What about calling it css_class() ?
Is it really a "css" class? Isn't it a class for a html element, that can be used in css and js to access that html element?
It generates a some css classes.
Closing the issue so that all the discussion happens on the PR.
@lyrixx I think @gharlan is right. It generates HTML classes.
Most helpful comment
I like this proposal ... but I'm not a big fan of the proposed function names. Although Twig is for front-end people, it's used by lots of backend people, so "classes" sounds like programming classes, not CSS classes.
Also, front-end people use classes in JavaScript ... so it may be confusing to them too.
What about calling it
css_class()? There's no need to use plural because in Twig we always use singular even when the usage is plural (e.g.include()and notincludes())