Ruby-on-rails 如何在 Haml 中制作动态 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2217583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make dynamic ids in Haml?
提问by user225643
#item
creates a div with id="item"
创建一个 id="item" 的 div
.box#item
creates a div with class="box" and id="item"
创建一个 class="box" 和 id="item" 的 div
.box#="item "+x
creates a div with class="box" and a comment '#="item"+x'
创建一个带有 class="box" 和注释 '#="item"+x' 的 div
.box#
="item"+x
throws "Illegal element: classes and ids must have values."
抛出“非法元素:类和 ID 必须有值。”
How do I get set the id to a variable?
如何将 id 设置为变量?
回答by EmFi
There are two ways:
有两种方式:
The long form way (define the id as if it were a regular attribute):
长格式方式(将 id 定义为常规属性):
.box{:id => "item_#{x}"}
produces this (xis what ever x.to_sevaluates to):
产生这个(x是曾经x.to_s评估过的):
<div class="box" id="item_x">
The short form way:
简写方式:
.box[x]
produces the following assuming xis an instance of item:
产生以下假设x是一个实例item:
<div class="box item" id="item_45">
See the HAML referencefor more information.
有关更多信息,请参阅HAML 参考。
回答by Deepak Mahakale
You can set the idand classin HAML the following ways
您可以通过以下方式在 HAML 中设置id和class
The normal way
.box.item#item<div id="item" class="box item"></div>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>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>If you need to prefix something
.box[@item, :custom]<div id="custom_item_123" class="box custom_item"></div>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 endAnd then you will get the customized class
.box[@item]<div id="customized_item_123" class="box customized_item"></div>
正常方式
.box.item#item<div id="item" class="box item"></div>如果你需要插值,你可以使用这种格式
.box{id: "item_#{123}", class: "item_#{123}"}<div id="item_123" class="box item_123"></div>此格式使用对象引用生成类和 id
# app/controllers/items_controller.rb @item = Item.find(123).box[@item]<div id="item_123" class="box item"></div>如果你需要加前缀
.box[@item, :custom]<div id="custom_item_123" class="box custom_item"></div>如果您需要自定义类和 id 生成,则需要将以下方法添加到模型中。
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:
参考:

