Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering partials from a helper method

Is it possible to render a partial using a helper method where you can also pass local variables from the view in which the helper method is called? For example, when I include this code directly in the view, it renders the partial properly:

 <%= render :partial => "add_round", :locals => { :f => f } %>

Then I moved it to a helper method:

def addRound
  render :partial => "add_round", :locals => { :f => f }
end

Then I called it from the view again with:

 <%= addRound %>

This did not work with the :locals => { :f => f } included in the code. It returned this error: undefined local variable or method `f'. However, the addRound method did render something with the following:

def addRound
  render :partial => "add_round"
end

Writing it this way allowed me to render partials that didn't require the local variables to be passed through (such as plain text strings). But how can I get it to work with the :locals => { :f => f } included? Is there another way to write that?

Thanks so much.

like image 832
Josh Avatar asked Sep 11 '12 01:09

Josh


People also ask

What is a helper method in Ruby?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .

What is render partial in rails?

Rails Guides describes partials this way: Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

What are partials in Ruby?

Partial templates (partials) are a way of breaking the rendering process into more manageable chunks. Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates.


1 Answers

You need to pass f to addRound

def addRound(f)
  render partial: "add_round", locals: { f: f }
end

and in the view

<%= addRound(f) %>
like image 98
deefour Avatar answered Sep 23 '22 20:09

deefour