gpt4 book ai didi

html - 在 rails 中定义 anchor 标记的正确方法是什么?

转载 作者:技术小花猫 更新时间:2023-10-29 12:08:58 25 4
gpt4 key购买 nike

documentation 可以明显看出(和谷歌)如何生成与段的链接,例如podcast/5#comments .您只需为 :anchor 传递一个值至 link_to .

我担心的是生成 <a name="comments">Comments</a> 的任务要简单得多标记,即第一个链接的目的地。

我已经尝试了以下方法,虽然它们似乎有效,但标记并不是我所期望的:

link_to "Comments", :name => "comments"
link_to "Comments", :anchor => "comments"

我想我遗漏了一些明显的东西。谢谢。

最佳答案

您对 Ruby 的语法糖(Rails 大量使用)感到困惑。在回答您的问题之前,让我简要解释一下。

当 ruby​​ 函数接受一个散列参数时:

def foo(options)
#options is a hash with parameters inside
end

你可以“忘记”放置圆括号/方括号,这样调用它:

foo :param => value, :param2 => value

Ruby 将填补空白并理解您要完成的是:

foo({:param => value, :param2 => value})

现在,对于您的问题:link_to 采用两个 可选哈希 - 一个称为 options,另一个称为 html_options。你可以想象它是这样定义的(这是一个近似值,它要复杂得多)

def link_to(name, options, html_options)
...
end

现在,如果您以这种方式调用它:

link_to 'Comments', :name => 'Comments'

Ruby 会有点困惑。它会尝试为您“填空”,但错误的是:

link_to('Comments', {:name => 'Comments'}, {}) # incorrect

它会认为name => 'Comments'部分属于options,而不属于html_options!

您必须自己填空来帮助 ruby​​。将所有括号放在适当的位置,它将按预期运行:

link_to('Comments', {}, {:name => 'Comments'}) # correct

如果需要,您实际上可以删除最后一组括号:

link_to("Comments", {}, :name => "comments") # also correct

不过,为了使用 html_options,您必须保留第一组括号。例如,您需要为带有确认消息和名称的链接执行此操作:

link_to("Comments", {:confirm => 'Sure?'}, :name => "comments")

其他 Rails 助手具有类似的构造(即 form_forcollection_select),因此您应该学习这种技术。有疑问,就把括号全部加上。

关于html - 在 rails 中定义 anchor 标记的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2091550/

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