gpt4 book ai didi

ruby-on-rails - Rails View 辅助函数和 link_to 函数

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:15 27 4
gpt4 key购买 nike

我正在尝试创建一个辅助函数(例如在 application_helper.rb 中),它根据传递给辅助函数的参数生成一个 link_to。如果我将链接放在 ERB 文件中,它将采用以下格式:

<%= link_to 'Some Text', { :controller => 'a_controller', :action => 'an_action' } %>

在helper函数中,Text、Controller、Action都是传入或者计算出来的。辅助函数中的代码是:

params = "{ :controller => '#{controller}', :action => '#{action_to_take}'}"
html = "#{link_to some_text, params }<p />"
return html

生成的链接具有正确的文本,但参数实际上是 params 字符串的内容。

如何获取要评估的 params 字符串(因为它在 ERB 文件中)?

最佳答案

我认为您脑子里的事情过于复杂了。除非你想做一些非常奇怪(而且不可取)的事情,否则这会起作用:

def link_helper text, controller, action
link_to text, :controller => controller, :action => action
end

不过,如您所见,不值得将其作为助手 - 它几乎不比它包装的功能简单,而且灵 active 要差得多。

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

关于ruby-on-rails - Rails View 辅助函数和 link_to 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4668616/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com