1

我想要一个像 link_to 一样工作的助手,只是它合并到一个数据属性中(在这种情况下,为了便于使用引导程序创建选项卡:http: //twitter.github.com/bootstrap/javascript.html#tabs )

所以我可以这样称呼它:

link_to_tab("Name", @obj)

并得到

<a href='/path' data-toggle='tab'>Name</a>

我想出了这个似乎可行的方法:

def link_to_tab(*args, &block)
  toggle_hash = {'data-toggle' => 'tab'}
  last_arg = args.pop # if link_to was given a hash of html_options, merge with it
  if last_arg.is_a? Hash
    link_to(*args, last_arg.merge(toggle_hash), &block)
  else
    link_to(*args, last_arg, toggle_hash, &block)
  end
end

是否有一种更简洁、更惯用的方式来支持所有调用 link_to 的方式?

4

2 回答 2

2

并不真地。你可以试试这个...

def link_to_tab(*args, &block)
  toggle_hash = {'data-toggle' => 'tab'}
  if args.last.is_a? Hash
    args.last.merge!(toggle_hash) 
  else
    args << toggle_hash
  end
  link_to(*args, &block)
end

虽然没有那么不同...

于 2013-01-03T19:39:21.610 回答
1

I'd like to have a helper that works just like link_to except that it merges in a data attribute

I might be missing something, but why not just pass a custom data argument to the link_to helper?

= link_to "foo tab", {}, "data-toggle" => "tab"

Outputs:

<a data-toggle="tab" href="/">foo tab</a>

Edit

If you're planning on using it a lot you can do:

def link_to_tab(*args, &block)
  if args.last.is_a? Hash
    link_to *(args.take args.size - 1), args.last.merge("data-tab" => "tab"), &block
  else
    link_to *args, "data-tab" => "tab", &block
  end
end
于 2013-01-04T00:00:17.690 回答