-
Notifications
You must be signed in to change notification settings - Fork 10.8k
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
[8.x] @class
Blade directive
#38016
[8.x] @class
Blade directive
#38016
Conversation
src/Illuminate/Collections/Arr.php
Outdated
* @param array $array | ||
* @return string | ||
*/ | ||
public static function toClasses($array) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the method does stay here, it toCssClasses
may be a better name so the context of what the method does is clear when the Arr
class is used outside Blade.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah it was a bit of a struggle to find an appropriate name, toCssClasses
sounds good but lets see what the Laravel team think 👍
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wouldn't toHtmlClasses
be more appropriate? The point is that this is in the context of view templates, but it's not related to styling necessarily. You could have @class(['clickable' => $enabled])
to control some JavaScript logic for instance.
@taylorotwell What do you think about the conversation above suggesting the use of |
I'll open a PR for the docs 🎉 Update: laravel/docs#7194 |
Hey! 👋
Conditional class syntax for Blade component attribute bags has been available in Laravel since v8.27.0. It can be used to conditionally merge attributes into the bag based on Boolean expressions, like so:
In this example, the
font-bold
class would be merged into this class list when the component is$active
.I would like to expand the scope of this syntax one step further, and make it available in a
@class
Blade directive. Similar functionality can be found in many frontend frameworks, including Vue.js and Alpine.js. This will allow Blade developers to use conditional classes on any HTML element, not just when merging them into the attribute bag. For example:To keep this new directive DRY, I extracted the class array compilation logic into a new array helper,
Arr::toCssClasses()
. Let me know if there is a better place to put this logic!Alternative
Alternatively, I could remove the
@class
Blade directive and allow developers to use the rawArr::toCssClasses()
helper, like so: