我正在尝试创建一个辅助函数(例如在application_helper.rb
中),该函数根据传递给辅助函数的参数生成link_to
。如果我将链接放在ERB文件中,则格式为:
<%= link_to 'Some Text', { :controller => 'a_controller', :action => 'an_action' } %>
在辅助函数中,Text,Controller和Action都被传入或计算。辅助函数中的代码是:
params = "{ :controller => '#{controller}', :action => '#{action_to_take}'}"
html = "#{link_to some_text, params }<p />"
return html
生成的链接具有正确的文本,但参数实际上是params
字符串的内容。
如何获得要评估的params
字符串(因为它在ERB文件中)?
答案 0 :(得分:10)
我认为你头脑中的事情过于复杂。除非你试图做一些非常奇怪(并且不可取)的事情,否则这会起作用:
def link_helper text, controller, action
link_to text, :controller => controller, :action => action
end
虽然你可以看到它不值得帮助它 - 但它几乎不比它包装的功能简单得多,而且灵活性要低得多。
link_to帮助器返回一个字符串,因此以您想要的方式使用它非常简单:
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
答案 1 :(得分:0)
你可以简单地使用url_for帮助器。
link_to“Some Text”,url_for(:action =&gt;:action_name,:controller =&gt;:controller_name)