简体   繁体   English

Haml与Rails:将表格列变成链接

[英]Haml with Rails: making a table column into a link

I'm creating a haml table like so: 我正在创建一个haml表,如下所示:

%tbody
  - @records.each do |br|
    %tr
      %td.name
        = br.full_name
      %td.address
        = br.address

I would like to create a link from the entire tr to another page. 我想创建一个从整个tr到另一个页面的链接。 How can I do this? 我怎样才能做到这一点?

Because nesting any block level element inside an <a> tag is illegal. 因为在<a>标记内嵌套任何块级元素都是非法的。 I would do it using jQuery. 我会使用jQuery。

%tr{"data-link" => url_for(:action => 'show', :id => br.id)}
  %td.name
    = br.full_name
  %td.address
    = br.address

Then, at the end of the table: 然后,在表末尾:

:javascript
  $("tr[data-link]").click(function() {
    window.location = this.data("link")
  })

You should also include a stylesheet that changes the mouse cursor to a pointer. 您还应该包括一个样式表,该样式表将鼠标光标更改为指针。

:stylesheet
  #yourtable tr
    cursor: pointer;

You should be able to pass the row as a block to link_to : 您应该能够将该行作为一个块传递给link_to

link_to(url, html_options = {}) do
  #row
end

EDIT: 编辑:

- link_to(url, html_options = {}) do
  %tr
    %td.name
      = br.full_name
    %td.address
      = br.address

EDIT BY OP: this ended up working: 按OP编辑:这最终可以工作:

  %tr
    %td.name
      = link_to(br.full_name, html_options = {:action => 'show', :id => br.id})

Here's how I did it in Rails 4.0.2. 这是我在Rails 4.0.2中完成的方法。 My controller's name is order . 我的控制器的名称为order

Assign an id to your table so you can identify it via CSS later; 为您的表分配一个ID,以便以后可以通过CSS进行标识; I used the id orders . 我使用了id orders

For each table row that contains a data cell, add the "data-link" attribute to it with the value of the link (in my case it looks like /orders/1 and so on). 对于包含数据单元格的每个表行,将“ data-link”属性与链接的值添加到该行(在我的情况下,它看起来像/orders/1 ,依此类推)。

app/views/orders/index.html.haml

%table#orders
  %tr
    %th ...
    .
    .
    .
  - @orders.each do |order|
    %tr{"data-link" => order_path(order)}
      %td= ...
      .
      .
      .

In your JavaScript file (or CoffeeScript file as shown here), create the links for the table rows that have the "data-link" attribute with their respective "data-link" values. 在您的JavaScript文件(或此处显示的CoffeeScript文件)中,为具有“数据链接”属性的表行创建链接,并为其各自的“数据链接”值创建链接。

app/assets/javascripts/order.js.coffee

$ ->
  $("tr[data-link]").click ->
    window.location = @dataset.link

In the stylesheet for your controller, make the cursor change into a pointer when hovering over the rows to indicate that they are clickable. 在控制器的样式表中,将鼠标悬停在行上以指示它们可单击时,将光标更改为指针。

app/assets/stylesheets/order.css.scss

#orders tr[data-link] {
  cursor: pointer;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM