Reputation: 3288
my question concerns about Rails + HAML
I would like to conditionally set a class atribute to a HTML tag. I figured out that the best way to do this is by setting controller variables that are used to set a class of the appropriate HTML tag.
The only solutions I found googling tell me to use a conditional in HAML. But I don't think this is the best approach, since Views shouldn't have any logic control.
So, how could I do this directly from the controller? Which are those controller variables that can set a class of a html tag?
Upvotes: 1
Views: 1389
Reputation: 284
For simple logic (like setting a class) you can use haml_tag that exposes class attribute value as a string:
- haml_tag :th, class: "#{'hilite' if params[:order_by]=='title'}" do
- haml_concat link_to 'Movie Title', movies_path(order_by: 'title')
This way you still have conditional logic in the view but resorting to helper in this case may be an overkill.
Upvotes: 1
Reputation: 25739
Haml indeed discourages using logic in views and makes it easy to create helpers instead. So one solution would be to create your helper method with any logic inside.
You can't control html markup from controllers, the views are for this purpose. If you don't want to create a separate helper (it's too much for your requirements), use existing tag helper that comes with rails. It accepts a hash of options which can be intialized from your controller if you like.
But again, I'd go for helper.
Upvotes: 1
Reputation: 4807
If you don't want logic in your haml templates then you should move it into a helper. There's really no way for a controller to set the class for a specific html tag; that's not what controllers are for.
Upvotes: 0