什么是在轨道中定义锚标签的正确方法? [英] What's the right way to define an anchor tag in rails?
问题描述
从文档(和google)中可以明显看出生成与分段的链接,例如播客/ 5#评论
。您只需将:anchor
的值传递给 link_to
。
It's obvious from the documentation (and google) how to generate a link with a segment e.g. podcast/5#comments
. You just pass a value for :anchor
to link_to
.
我关心的是生成< a name =comments>评论< / a>
标签,即第一个链接的目的地。
My concern is about the much simpler task of generating the <a name="comments">Comments</a>
tag i.e. the destination of the first link.
我尝试了以下方法,虽然它们似乎可行,但标记并非我所期望的:
I've tried the following, and although they seemed to work, the markup was not what I expected:
link_to "Comments", :name => "comments"
link_to "Comments", :anchor => "comments"
我想我错过了一些明显的东西。感谢。
I think I'm missing something obvious. Thanks.
推荐答案
当一个ruby函数接受一个散列值的单个参数时:
When a ruby function takes a single parameter that is a hash:
def foo(options)
#options is a hash with parameters inside
end
您可以'忘记'放置括号/括号,然后像这样调用它:
You can 'forget' to put the parenthesis/brackets, and call it like this:
foo :param => value, :param2 => value
Ruby会填补空白,并且明白您要完成的是: p>
Ruby will fill out the blanks and understand that what you are trying to accomplish is this:
foo({:param => value, :param2 => value})
现在,对于您的问题: link_to
需要两个可选哈希 - 一个名为 options
,另一个 html_options
。你可以想象它是这样定义的(这是一个近似值,它更复杂)
Now, to your question: link_to
takes two optional hashes - one is called options
and the other html_options
. You can imagine it defined like this (this is an approximation, it is much more complex)
def link_to(name, options, html_options)
...
end
现在,如果您调用它方式:
Now, if you invoke it this way:
link_to 'Comments', :name => 'Comments'
Ruby会有点困惑。它会尝试为你填补空白,但不正确:
Ruby will get a little confused. It will try to "fill out the blanks" for you, but incorrectly:
link_to('Comments', {:name => 'Comments'}, {}) # incorrect
它会认为 name => '评论'
部分属于选项,而不是 html_options
!
It will think that name => 'Comments'
part belongs to options, not to html_options
!
您必须通过自己填补空白帮助红宝石。
You have to help ruby by filling up the blanks yourself. Put all the parenthesis in place and it will behave as expected:
link_to('Comments', {}, {:name => 'Comments'}) # correct
如果你想要删除最后一组括号:
You can actually remove the last set of brackets if you want:
link_to("Comments", {}, :name => "comments") # also correct
为了使用html_options,您必须保留第一组括号。例如,您需要为链接提供确认消息和名称:
In order to use html_options, you must leave the first set of brackets, though. For example, you will need to do this for a link with confirmation message and name:
link_to("Comments", {:confirm => 'Sure?'}, :name => "comments")
助手具有类似的构造(即 form_for
, collection_select
),所以您应该学习这种技巧。如有疑问,只需添加所有括号即可。
Other rails helpers have a similar construction (i.e. form_for
, collection_select
) so you should learn this technique. In doubt, just add all the parenthesis.
这篇关于什么是在轨道中定义锚标签的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!