【问题标题】:data attributes in li class?li 类中的数据属性?
【发布时间】:2014-01-09 09:41:19
【问题描述】:

我的模型中有这段代码:

def features_to_html_class  
   "mix #{bedrooms} #{region.name}  #{categories.map{|cat|cat.name}.join(' ')}"
end

在我看来这个

- @regions.each do |region|
   - @houses.where(region_id: region.id).each do |house|
     %li{:class => house.features_to_html_class }

HTML 输出如下:

<li class='mix 3 umbria price_range-1 villa_with_pool '>

这项工作正常,但现在我想将数据属性“数据排序”和“数据顺序”添加到 li 类。所以我有这个 HTML 输出

<li class="mix 3 umbria price_range-1 villa_with_pool" data-sort="data-name" data-order="desc">

我必须如何更改 features_to_html_class 方法才能实现这一点?

谢谢...remco

【问题讨论】:

  • 试试%li{:class =&gt; house.features_to_html_class, data-sort: "data-name", data-order: "desc"}
  • 这些值('data-name''desc')是固定的还是动态获取的?
  • 谢谢...这些值是动态的
  • 那么你必须为此创建单独的方法

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 haml


【解决方案1】:

要在 Haml 中添加新属性,您只需将它们作为散列传递 ('attribute_name' => 'value')

以下应该做的

- @regions.each do |region|
   - @houses.where(region_id: region.id).each do |house|
     %li{:class => house.features_to_html_class, "data-sort" => "data-name", "data-order" => "desc"}

编辑:

为什么不能在视图中使用您对方法“features_to_html_class”的更改,因为 你直接写了类属性(li元素的类中附加的值)

%li{:class =&gt; house.features_to_html_class }

【讨论】:

    【解决方案2】:

    这应该可行:

    %li{class: house.features_to_html_class, data: {sort: 'data-name', order: 'desc'}}
    

    更新

    由于您的数据值是动态的,您可以更改方法以提供整个属性哈希:

    def features_to_html_attributes  
      {
        class: "mix #{bedrooms} #{region.name} #{categories.map{|cat|cat.name}.join(' ')}",
        data: {sort: 'data-name', order: 'desc'}
      }
    end
    

    并通过以下方式分配:

    %li{features_to_html_attributes}
    

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      相关资源
      最近更新 更多