gpt4 book ai didi

ruby-on-rails - Rails 将 block 传递给辅助方法

转载 作者:行者123 更新时间:2023-12-03 16:09:06 26 4
gpt4 key购买 nike

Viget Labs 发布 an articlegist详细说明用于将特定类(如 .selected.active )添加到导航链接(如果其 url 与当前路径匹配)的 rails helper 方法。

您可以像这样在布局中使用它:

= nav_link "News", articles_path, {class: "btn btn-small"}

<!-- which creates the following html -->

<a href="/articles" class="btn btn-small selected">News</a>

好的。我正在使用 bootstrap ,并希望在我的按钮中有一个图标,因此我需要生成以下 html:
<a href="/articles" class="btn btn-small selected"><i class="icon-home"> </i> News</a>

forked the gist并想出了一个简单的方法。我的 fork 让开发者通过 :inner_html :inner_class 像这样的助手:
= nav_link "News", articles_path, {class: "btn btn-small"}, {inner_html: 'i', inner_class: 'icon-home'}

它工作正常,但我不喜欢我的底层实现:
def link
if @options[:inner_html]
link_to(@path, html_options) do
content_tag(@options[:inner_html], '', :class => @options[:inner_class]) + " #{@title}"
end
else
link_to(@title, @path, html_options)
end
end

如您所见,我将新选项传递给 content_tag在 link_to 方法的块内。我希望我能够以几种方式重构它。

首先,在我看来,我希望能够做到这一点:
= nav_link "News", articles_path, {class: "btn btn-small"} do
%i.icon-home

我想将内部 html 作为一个块,而不是作为选项哈希的属性。谁能给我任何关于如何实现这一目标的指示?

我认为这是告诉 nav_link 方法接受一个块的简单情况:
def nav_link(title, path, html_options = {}, options = {}, &block)
LinkGenerator.new(request, title, path, html_options, options, &block).to_html
end

class LinkGenerator
include ActionView::Helpers::UrlHelper
include ActionView::Context

def initialize(request, title, path, html_options = {}, options = {}, &block)
@request = request
@title = title
@path = path
@html_options = html_options
@options = options
@block = block
end

def link
if @block.present?
link_to @path, html_options do
@block.call
@title
end
end
end

但这无法输出图标,而是插入一个数字 (4)。我不清楚。任何人都有任何建议。我可以去哪里阅读有关此类事情的更多信息,因为我真的希望能够在不必询问 stackoverflow 的情况下弄清楚这样的事情。

最佳答案

我尝试了您的问题,以下在助手中对我非常有效:

  def my_link(title, path, &block)
if block_given?
link_to path do
block.call
concat(title)
end
else
link_to title, path
end
end

用法:
my_link "No title", User.first do
%i.icon-home

关于ruby-on-rails - Rails 将 block 传递给辅助方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11902910/

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