Twig: [RFC] Added support for classes function

Created on 8 Jan 2019  路  7Comments  路  Source: twigphp/Twig

The classes function in javascript is quite useful.
Do you think it could be in twig ?
I would port it if you want

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 not includes())

All 7 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Seldaek picture Seldaek  路  6Comments

SDPrio picture SDPrio  路  3Comments

dvladimirov77 picture dvladimirov77  路  5Comments

rungta picture rungta  路  3Comments

koflerdavid picture koflerdavid  路  3Comments