Rails view Helper function and the link_to function
I am trying to create a helper function (eg in application_helper.rb
) that generates a link_to
based on parameters passed in to the helper function. If I were putting the link in an ERB file it would be of the format:
<%= link_to 'Some Text', { :controller => 'a_controller', 开发者_运维技巧:action => 'an_action' } %>
In the helper function, the Text, Controller and Action are all passed in or calculated. The code in the helper function is:
params = "{ :controller => '#{controller}', :action => '#{action_to_take}'}"
html = "#{link_to some_text, params }<p />"
return html
The link that is generated has the correct text, however the parameters are literally the contents of the params
string.
How can I get the params
string to be evaluated (as it is in an ERB file)?
I think you have things overcomplicated in your head. Unless you're trying to do something very odd (and inadvisable) this would work:
def link_helper text, controller, action
link_to text, :controller => controller, :action => action
end
Although, as you can see it's not worth making it a helper - it's barely any more simple than the functionality it's wrapping, and much less flexible.
The link_to helper returns a string, so it's very simple to use in the way you want:
def link_helper text
# some helper logic:
controller = @controller || "pages"
action = @action || "index"
# create the html string:
html = "A link to the #{controller}##{action} action:"
html << link_to(text, :controller => controller, :action => action)
html # ruby does not require explicit returns
end
You could simple use url_for helper .
link_to "Some Text", url_for(:action=> :action_name , :controller=> :controller_name )
精彩评论