[英]How can I add rails code to id attribute in div tag?
我想做這樣的事情: <div id="<%=service.name%>"
但是,我無法讓它發揮作用。 我需要幫助! 我試圖為點擊的每個按鈕創建一個模態,但只在 html.erb 中的模態 div 上。
要使模態工作,它們需要具有相同的 ID。
<% @services.each do |service| %>
<div class="card">
<a class="card-b" href="#" data-toggle="modal" data-target="# <%=service.name%> ">
</div>
<div class="modal" id=" <%=service.name%> " tabindex="-1" role="dialog" aria-hidden="true">
Hello this is the modal.
</div>
<% end %>
我想在ID標簽中使用rails代碼,不知道是否可以?
編輯:
我嘗試了最好的答案,它只對少數模態有效,其余的則無效。 然后我在我的表中添加了一個modal_tag
列,所有的模態都起作用了。 謝謝!
我的代碼現在是id="<%=service.modal_tag%>
我的偏好是使用像engineersmnky
指出的SecureRandom.hex
或__id__
這樣的唯一值,而不是使用模型 ID。 代碼看起來像這樣:
# You may also have to require 'securerandom' within your rails app
# (can't remember if that comes in automatically or not)
<% @services.each do |service| %>
<!-- Either option for random_id works below -->
<% random_id = SecureRandom.hex %>
<% random_id = service.__id__ %>
<div class="card">
<a class="card-b" href="#" data-toggle="modal" data-target="#<%= random_id %>">
</div>
<div class="modal" id="<%= random_id %>" tabindex="-1" role="dialog" aria- hidden="true">
Hello this is the modal.
</div>
<% end %>
我更喜歡這個的原因是它不會泄漏數據庫 ID(如果這是您關心的事情),並且在此模式嵌入其他頁面的情況下,您不太可能發生 id 沖突。
給出一個簡單的基准測試腳本,看起來__id__
是兩個選項中性能更高的:
$ cat unique_id.test.rb
require 'securerandom'
require 'benchmark'
n = 100_000
Benchmark.bm do |x|
x.report { n.times do |n| ; SecureRandom.hex; end }
x.report { n.times do |n| ; n.__id__ ; end }
end
$ ruby unique_id.test.rb
user system total real
0.180000 0.000000 0.180000 ( 0.176293)
0.000000 0.000000 0.000000 ( 0.005554)
Ruby on Rails 有一個dom_id
方法來生成唯一的 id,以便在 HTML 文檔中使用。 此外,我不喜歡混合 HTML 標簽和 ERB——因此我可能會使用輔助方法
# in a helper
def service_modal(service, &block)
tag.div(class: 'card') do
tag.a(class: 'card-b', data: {toggle: 'modal', target: dom_id(service) }, href: '#')
end +
tag.div(class: 'modal', dom_id(service), tabindex: 1, role: 'dialog', 'aria-hidden': 'true') do
capture(&block)
end
end
並像這樣使用它
# in the view
<% @services.each do |service| %>
<%= service_modal(service) do %>
Hello this is the modal.
<% end %>
<% end %>
此外,您可以使用object_id
。
Rails: data-target="#<%= service.object_id %>">
基准:
user system total real
0.071505 0.000187 0.071692 ( 0.072017) #SecureRandom.hex
0.004685 0.000016 0.004701 ( 0.004727) #__id__
0.004500 0.000001 0.004501 ( 0.004503) #object_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.