【问题标题】:Rails and haml, how to add id and class selectors to link_to helper?Rails和haml,如何将id和类选择器添加到link_to helper?
【发布时间】:2013-02-02 02:40:06
【问题描述】:

我一直在寻找如何使用hamlid 选择器添加到link_to 助手,这可能吗?

  a .haml - %a#booked{:href => "index.haml"} Link 1    

  b .html.erb - booking.html.erb - <%= link_to "Link 1", booking_path, :id => "booked" %>

  c .haml.erb - booking.haml.erb - ...??

haml 中哪个相当​​于 b?

【问题讨论】:

    标签: ruby-on-rails-3 haml


    【解决方案1】:

    link_to 在haml 中的工作方式与在erb 中的工作方式完全相同。所以这会做你想做的事:

    = link_to "Link 1", booking_path, :id => "booked"
    #=> <a id="booked" href="/bookings">Link 1</a>
    

    你也可以这样分配一个类属性:

    = link_to "Link 1", booking_path, :id => "booked", :class => "some_class"
    #=> <a id="booked" class="some_class" href="/bookings">Link 1</a>
    

    更多关于如何在haml中插入ruby代码:Inserting ruby

    而且,毫无疑问,将 id 和类传递给 link_to,这是一个示例 from the docs

    link_to "Articles", articles_path, :id => "news", :class => "article"
    #=> <a href="/articles" class="article" id="news">Articles</a>
    

    【讨论】:

    • 嗨@shioyama,这种方法会在url中添加一个id。我正在寻找的是添加一个 id 选择器,例如 link 1 .
    • 这正是它的作用:&lt;a id="booked" href="..."&gt;Link 1&lt;/a&gt;。它不会将其添加到 url。
    • 我在link_to 上的文档中添加了一个示例,您可以看到id 将正确分配给a 标记,而不是附加到URL。
    • 谢谢你,@shioyama 帮助很大。
    • @shioyama 有没有办法使用更现代的 ruby​​ 表示法,例如:{class:'article'}
    【解决方案2】:

    要使用 link_to 在 haml 中添加 id 选择器,您必须指定两个哈希值。

    e.g = link_to "Link 1", {booking_path, extra arg...}, {:id => 'booked'}
    

    一个重要的 Ruby 习语是 诗歌模式:当解析明确时省略括号和花括号的能力。最常见的是,Ruby 程序员可能会在方法调用的参数周围省略括号,并在方法调用的最后一个参数是散列时省略花括号。因此,以下两个方法调用是等效的,给定一个方法 link_to,它接受一个字符串参数和一个哈希参数:

    没有花括号,就无法判断此调用是尝试传递具有两个键的散列还是每个键的两个散列。因此,诗歌模式只能在有单个哈希参数并且是最后一个参数时使用。

    帕特森,大卫;福克斯,阿曼多 (2012-08-24)。工程持久软件:使用 SaaS 和云计算的敏捷方法,Beta 版(Kindle Locations 1973-1975)。草莓峡谷有限责任公司。 Kindle版。

    【讨论】:

    • 在这种情况下,您不需要 传递两个哈希值,link_to "Link 1", booking_path, :id =&gt; "booked" 可以正常工作。
    • 感谢您使用大括号,不使用它们是这对我不起作用的原因。 &lt;%= link_to 'Video Index', controller: 'videos', :id =&gt; 'index' %&gt; 输出 &lt;a href="/videos?id=index"&gt;Video Index&lt;/a&gt; 但将其更改为此 {controller: 'videos'} 使其正确输出 &lt;a id="index" href="/videos"&gt;Video Index&lt;/a&gt;
    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2012-03-26
    • 1970-01-01
    • 2014-05-24
    相关资源
    最近更新 更多