在 Rails 中定义锚标记的正确方法是什么?
从文档(和谷歌)中可以明显看出如何生成与片段链接,例如 podcast/5#comments
。您只需将 :anchor
的值传递给 link_to
即可。
我关心的是生成 Comments 标记(即第一个链接的目的地)的更简单的任务。
我尝试了以下方法,虽然它们似乎有效,但标记不是我所期望的:
link_to "Comments", :name => "comments"
link_to "Comments", :anchor => "comments"
我认为我错过了一些明显的东西。谢谢。
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
.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您对 Ruby 的语法糖(Rails 大量使用)感到困惑。在回答你的问题之前,让我先简单解释一下。
当 ruby 函数采用单个散列参数时:
您可以“忘记”放置圆括号/方括号,并像这样调用它:
Ruby 会填写空白并理解您要完成的任务是:
现在,对于您的问题:
link_to
采用两个可选哈希 - 一个称为options
,另一个称为html_options
。你可以想象它是这样定义的(这是一个近似值,它要复杂得多)现在,如果你这样调用它:
Ruby 会有点困惑。它会尝试为您“填写空白”,但这是错误的:
它会认为
name => 'Comments'
部分属于选项,而不是html_options
!你必须自己填补空白来帮助 ruby。将所有括号放在适当的位置,它将按预期运行:
如果需要,您实际上可以删除最后一组括号:
不过,为了使用 html_options,您必须保留第一组括号。例如,您需要对带有确认消息和名称的链接执行此操作:
其他 Rails 助手具有类似的结构(即
form_for
、collection_select
),因此您应该了解这一点技术。如有疑问,只需添加所有括号即可。You are getting confused by Ruby's syntactic sugar (which Rails uses profusely). Let me explain this briefly before answering your question.
When a ruby function takes a single parameter that is a hash:
You can 'forget' to put the parenthesis/brackets, and call it like this:
Ruby will fill out the blanks and understand that what you are trying to accomplish is this:
Now, to your question:
link_to
takes two optional hashes - one is calledoptions
and the otherhtml_options
. You can imagine it defined like this (this is an approximation, it is much more complex)Now, if you invoke it this way:
Ruby will get a little confused. It will try to "fill out the blanks" for you, but incorrectly:
It will think that
name => 'Comments'
part belongs to options, not tohtml_options
!You have to help ruby by filling up the blanks yourself. Put all the parenthesis in place and it will behave as expected:
You can actually remove the last set of brackets if you want:
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:
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.如果您想通过 Rails,我建议
content_tag
(文档)。例子:
If you want to go through rails, I suggest
content_tag
(docs).Example:
为 login.html ig 创建了一个锚标记
并供
使用
created an anchor tag for login.html i.g
and for
use