Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Rails: how do I conditionally add a html id tag?

To apply some styling to an html element, on the condition that the user is not signed in, I used the following code in my HTML:

<body>

    <% if user_signed_in? %>
        <%= render "layouts/header" %>
    <% end %>

    <div class="container">
        <% flash.each do |name, msg| %>
            <%= content_tag(:div, msg, class: "alert alert-info") %>
        <% end %>
        <%= yield %>

        <% unless user_signed_in? %>
            <style>#pins {  -webkit-filter: blur(8px);
                            filter: blur(8px);
                            -moz-filter: blur(8px);
                            -o-filter: blur(8px);
                            -ms-filter: blur(8px);
                            }</style>
        <% end %>
    </div>
</body>

I don't like this though, because it's bad practice to style in your html.

How do I conditionally add an id tag instead?

You can see the full code on my github here: https://github.com/Yorkshireman/pinteresting/blob/master/app/views/layouts/application.html.erb

I guess I could wrap two sets of html in an if else statement. That would work. A bit bulky though.

1 Answer

Brandon Barrette
Brandon Barrette
20,485 Points

You should instead move the CSS into a CSS file, then in your view I would use the conditional statement to add the class to the element that you want to apply.

<div class="<%= user_signed_in? ? 'user-signed-in' : ' ' %>"></div>

You could also move this into a helper to clean up the view.