Conditionally setting CSS style from ruby controller
Be careful not to put logic (even conditionals) in your views if you can find a way around it. In order to avoid this common mistake, you need to make good use of the params and session hashes and set appropriate variables in controllers
# In your view
%th{:class => @title_header}= link_to 'Title', my_path(:sort => 'title'), :id => 'title_header'
# In your controller
sort = params[:sort] || session[:sort]
if sort == 'title'
ordering = {:order => :title}
end
How can i conditionally style a li in rails?
if each li is linked to different controller you can use controller_name
to add or not the selected
class
Here is an example from my app, it's in haml
%ul
%li
%a{:href => '/kebabs', :class => ('current' if controller_name == 'kebabs')} Admin kebabs
%li
%a{:href => '/statistics', :class => ('current' if controller_name == 'statistics')} Statistiques
%li
%a{:href => '/people', :class => ('current' if controller_name == 'people')} Admin Personnes
cheers
What's an elegant way to conditionally add a class to an HTML element in a view?
I use the first way, but with a slightly more succinct syntax:
<div class="<%= 'ok' if @status == 'success' %>">
Though usually you should represent success with boolean true
or a numeric record ID, and failure with boolean false
or nil
. This way you can just test your variable:
<div class="<%= 'ok' if @success %>">
A second form using the ternary ?:
operator is useful if you want to choose between two classes:
<div class="<%= @success ? 'good' : 'bad' %>">
Finally, you can use Rail's record tag helpers such as div_for
, which will automagically set your ID and class based on the record you give it. Given a Person
with id 47:
# <div id="person_47" class="person good">
<% div_for @person, class: (@success ? 'good' : 'bad') do %>
<% end %>
Conditional classname and text (Rails)
You can clean your controller tyres_controller.rb
(i suppose) method,
def show
@tyre = Tyre.find(params[:id]) # I believe you have a model named 'tyre'
end
Then, there will be a file named tyres_helper.rb
in your myproject/app/helpers/
. Put the following code there,
def tyre_availability(tyre) # it'll return an array with two values, first one is class name, second one is localized value
if tyre.in_stock
return 'i-check-circle color--success', I18n.t("products.filter.other.in_stock")
else
return 'i-cross-circle color--important', I18n.t("products.filter.other.not_in_stock")
end
end
and, in the view you can use,
.xs-12.description__status
%i{:class => tyre_availability(@tyre)[0]}
= tyre_availability(@tyre)[1]
conditional loading of stylesheet
If themes are large, you might want to separate them from the application.css and load them conditionally in your layout. For example, if you have a helper theme_stylesheet
in application_helper which returns the name of the theme the client is using:
# application.html.erb
<%= stylesheet_link_tag 'application', theme_stylesheet %>
If they are small, I like namespacing. Leave your application.css as-is, but modify the themes to use a top-level rule on the body. Place a tag on the body to select the theme. The beauty of this is you can dynamically change the theme.
<body class="theme-<%= theme_stylesheet %>">
...
</body>
_theme_x.css.scss
body.theme-x {
...
}
How to add conditional classes in rails?
Try <div id="<%= x.description.size < 50 ? 'smalldiv' : 'largediv' %>" >
You had ... quotes around 50, too many if
statements in a row, a missing =
in your <%
, and a gap if .size
equals exactly 50.
Rails Asset Pipeline with conditional CSS files
i have a project with similar requirements and i use the techniques shown in the linked answer:
# app/views/layouts/application.html.haml
= stylesheet_link_tag "application", "labels/#{Whitelabel[:label_id]}"
# config/application.rb
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( active_admin.js active_admin.css labels/* )
this includes an additional stylesheet, that is not included in the application.rb
have a look at the full source: https://github.com/phoet/on_ruby/
How to set css styles with variables in rails if certain item is selected?
I'm not sure what really is the best convention, but I think something like this would work:
<tr>
<%= stylized_th(@selected) { sortable "name" } %>
<%= stylized_th(@selected) { sortable "price" } %>
<%= stylized_th(@selected) { sortable "released_at", "Released" } %>
</tr>
With an additional helper:
def stylized_th(selected, &block)
content = capture(&block)
content_tag(:th, content, class: selected)
end
You can put some logic in there to determine what class to use based on the value of selected
. If you want no class, then use nil
.
I was inspired by this RailsCast:
http://railscasts.com/episodes/208-erb-blocks-in-rails-3
I hope it helps.
ruby on rails code syntax including some haml and model view control
:sort and :class are symbols in Ruby, representing identifiers that don't change in code the way a string can. They are being used as the key in a hash definition of keys/values.
When you pass a hash of name/value pairs to a tag like %th in HAML, it convents them into HTML attributes on the tag. This allows you to dynamically set the value of the "class" attribute on the TH tag with a list of class names from the instance variable @title_header.
my_path is a named route helper that represents a function to generate the URI for a route named in the Rails routeset. You can pass a variety of options to change how the URI is generated. By default, any option that isn't a route generation option gets injected as a query parameter on the URI generated. So if my_path => /my/path, then my_path(:foo => 'bar') => /my/path?foo=bar.
In this case, this query parameter likely dictates the sort order of the data generated at that URI.
In the same way, the link_to function takes an option hash as it's last argument that determines how the link element is generated. The last option set on this function is the html_options, where the attributes of the hash map to attributes of the A tag generated. In this case, the :id symbol and value in the hash will generate an "id" HTML attribute with the given value.
Since you asked, here's a good reference on what a CSS class is: http://www.tizag.com/cssT/class.php
Related Topics
Center Two Divs in The Middle of a Wrapper
CSS Bootstrap Overrides My Own CSS
Layering Images in CSS - Possible to Put 2 Images in Same Element
Setting Full Height of Angular Components
Bootstrap 4 Animate Column Width Change
Putting a Border Around Floating Elements
How to Use Font Awesome in Own CSS
Site 5X Faster via Mod_Rewrite, But CSS Images Are Broken
Two Divs Inside Div. How to Auto-Fill The Space of Parent Div by Second Div
Using an Icon Font (Font Awesome) Looks a Little Blurred and Too Bold
How Is The Caret on Twitter Bootstrap Constructed
Font Awesome Icons Are Not Working in Some Browsers
Way to Add Custom Class When Using Ngx-Bootstrap Modalservice
How to Write CSS Keyframes to Indeterminate Material Design Progress Bar
How to Add a Scroll Bar to a Component in React