【问题标题】:What's the right way to define an anchor tag in rails?在rails中定义锚标签的正确方法是什么?
【发布时间】:2011-01-06 16:28:33
【问题描述】:

documentation(和谷歌)可以明显看出如何生成带有段的链接,例如podcast/5#comments。您只需将:anchor 的值传递给link_to

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

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

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

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

【问题讨论】:

  • 很抱歉没有理解您清楚写的内容!我的错!很高兴你得到了你需要的答案。我删除了我的,以免混淆任何人:)

标签: html ruby-on-rails anchor hyperlink segment


【解决方案1】:

您对 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'部分属于选项,而不是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),所以你应该学习这种技术。如有疑问,只需添加所有括号即可。

【讨论】:

  • 这正是我想要的。谢谢!
【解决方案2】:

如果你想通过rails,我建议content_tagdocs)。

例子:

content_tag(:a, 'Comments', :name => 'comments')

【讨论】:

  • 谢谢,我想这就是我想要的。现在我突然想到,在 haml 中,只需 %a{:name => "comments"} Comments 即可建立该链接。我想我只是希望不要在 rails 中硬编码链接。
  • 有时只扔一个标签会更好,但如果你是erb'ing并且不想打破红宝石,这也很好:)
  • 我仍然喜欢这个答案,但我正在寻找 egarcia 的答案。
【解决方案3】:
<%= link_to('new button', action: 'login' , class: "text-center") %>

为 login.html i.g 创建了一个锚标记

<a href="login.html" class = "text-center"> new button </a>

对于

<a href="admin/login.html" class = "text-center"> new button </a>

使用

<%= link_to('new button', controller: 'admin',
    action: 'login' , class: "text-center") %>

【讨论】:

    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 2019-06-03
    • 2016-09-24
    • 1970-01-01
    相关资源
    最近更新 更多