How do I make dynamic ids in Haml?

#item

creates a div with id="item"

.box#item

creates a div with class="box" and id="item"

.box#="item "+x

creates a div with class="box" and a comment '#="item"+x'

.box#
="item"+x

throws "Illegal element: classes and ids must have values."

How do I get set the id to a variable?

36816 次浏览

有两种方式:

长形式方法(将 id 定义为常规属性) :

.box{:id => "item_#{x}"}

产生以下结果(xx.to_s的计算结果) :

<div class="box" id="item_x">

简单来说:

.box[x]

产生以下假设 xitem的实例:

<div class="box item" id="item_45">

有关更多信息,请参见 HAML 参考文献

可以通过以下方式在 HAML 中设置 idclass

  1. 正常的方式

    .box.item#item
    
    <div id="item" class="box item"></div>
    
  2. If you need to interpolation you can use this format

    .box{id: "item_#{123}", class: "item_#{123}"}
    
    <div id="item_123" class="box item_123"></div>
    
  3. This format generates the class and id using the object reference

    # app/controllers/items_controller.rb
    @item = Item.find(123)
    
    .box[@item]
    
    <div id="item_123" class="box item"></div>
    
  4. If you need to prefix something

    .box[@item, :custom]
    
    <div id="custom_item_123" class="box custom_item"></div>
    
  5. If you need a custom class and id generation you need to add the following method to model.

    class CrazyUser < ActiveRecord::Base
    def haml_object_ref
    "customized_item"
    end
    end
    

    然后你会得到定制的类

    .box[@item]
    
    <div id="customized_item_123" class="box customized_item"></div>
    

Refer: