3

I have a multiple partials that I am rendering and would like to add a CSS class to one of them. Is there a way to do this?

Here is the page I am rendering

<%= render :partial => "/account/plan_yearly" -%>

which adds this html to the page

<div class="offer">
    <!--MORE HTML-->
</div>

What I would like to do is something like this:

<%= render :partial => "/account/plan_yearly", :class => "highlight" -%>

Which would render the html below:

<div class="offer highlight">
    <!--MORE HTML-->
</div>

But it doesn't work the way I want it to. Any thoughts? Much appreciated!

Thanks Everyone

4 Answers 4

5

You will need to render the partial using locals and then use them within the partial:

<%= render partial: "/account/plan_yearly", locals: { myclass: 'highlight' } %>

What this does is make a local variable named myclass with a value of 'highlight' for the scope of the partial.

So in the partial you can then make use of this:

<div class="offer <%= myclass %>">
    <!--MORE HTML-->
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you both for helping me out! really appreciate it. I am having a new issue now. The partial is rendering <div class="offer #{myclass}"> with the #{ } and not as ruby. Any thoughts?
oops yeah should be erb shouldn't it - shall update the answer
Hey @David , I've been trying to get this exact same thing to work but i keep getting the following error: undefined local variable or method `myclass'. Any thoughts as to what I'm doing wrong?
1

Don't know if this might still help, but I just had the same problem, as it can be read on the rails documentation, in order to pass correctly values through locals it is really important to state explicitly taht you're randering a partial;

Correct:

<%= render partial:"path/to/partials", locals:{bla: "bla"} %>

Incorrect

<%= render "path/to/partials", locals:{bla: "bla"} %>

As the second line doesn't explicitly state that the rendering object is a partial, passing locals won't work at all...

Comments

0

You can pass it as variable

= render "/account/plan_yearly", highlight: true

Then in partial

<div class="offer #{'highlight' if highlight}">
  <!--MORE HTML-->
</div>

Comments

0

Passing it in as a variable worked!

<%= render partial: => "/account/plan_yearly", locals: { myclass: 'highlight' } %>

<div class="offer #{myclass}">
    <!--MORE HTML-->
 </div>

Thanks Everyone!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.