gpt4 book ai didi

ruby-on-rails - 将 link_to 选项作为可选项的 Rails 辅助方法

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

我正在尝试创建一个可以为 link_to 方法提供可选参数的辅助方法。我的目的是为不同的情况创建一个辅助方法:

# Typical case #1 (can have any number of extra arguments)
<%= toolbar_item('google.com', 'Google', 'globe', 'btn-primary', target: '_blank') %>

# Typical case #2 (extra arguments are optional)
<%= toolbar_item(root_path, 'Start', 'flag', 'btn-primary') %>

代码如下:

def toolbar_item(url,text,icon,custom_class, optional_extra_settings = {})
link_to raw("<i class='fa fa-#{icon}'></i> #{text}"), url, class: custom_class, optional_extra_settings
end

这样不好。 link_to 方法无法识别 extra_settings 并引发错误。

有什么想法吗?谢谢!

最佳答案

link_to方法只接受 3 个参数。最后一个参数需要是一个散列。因此,您必须将您的类(class)设置与可选的额外设置哈希合并。

将您的示例更改为:

def toolbar_item(url, text, icon, custom_class, optional_extra_settings = {})
html_options = { class: custom_class }.merge(optional_extra_settings)
link_to raw("<i class='fa fa-#{h icon}'></i> #{h text}"), url, html_options
end

此外,您会注意到我使用了 h 来转义您的 icontext。为了安全起见,因为您禁用了通常由 Rails 使用 raw 完成的自动转义。

关于ruby-on-rails - 将 link_to 选项作为可选项的 Rails 辅助方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35521742/

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