79
#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?

user225643
  • 3,601
  • 5
  • 27
  • 22

2 Answers2

139

There are two ways:

The long form way (define the id as if it were a regular attribute):

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

produces this (x is what ever x.to_s evaluates to):

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

The short form way:

.box[x]

produces the following assuming x is an instance of item:

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

See the HAML reference for more information.

Trevor
  • 75
  • 8
EmFi
  • 23,435
  • 3
  • 57
  • 68
  • 2
    i had to remove the whitespace to make it work: .box{:id => "item_#{x}"} – jethroo Feb 19 '13 at 17:14
  • how do you concatenate a string and a string-converted variable in the shortcut method? I tried `.box["item" + s]` and variants with no success. Is that shortcut way using square brackets only compatible with variables only? – ahnbizcad Jul 02 '14 at 00:18
  • 1
    @gwho the shortcut method requires x to be an instance of item. Use the long form string interpolation form to achieve what you're looking for. .box{:id => "item#{s}"} – EmFi Jul 02 '14 at 12:59
11

You can set the id and class in HAML the following ways

  1. The normal way

    .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
    

    And then you will get the customized class

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

Refer:

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88