简体   繁体   English

无法在 rails helper 中为 div 标签动态添加 id

[英]Can't dynamically add an id to div tag in rails helper

I'm having a very weird problem.我有一个非常奇怪的问题。 Here's my view:这是我的观点:

<h1>All Deals</h1>

  <%= sanitize print_grouped_deals(@deals) %>

Here's my deals_helper.rb这是我的 Deals_helper.rb

  def print_grouped_deals(grouped_deals_by_date)
    grouped_deals_by_date.map do |(date, deals)|
      %(<div id='#{date.to_s}-deals'>
        <h3>#{brief_time date}</h3>
          #{deal_paragraphs_for_group(deals)}</div>)
    end.join
  end

  def deal_paragraphs_for_group(deals)
    deals.map do |deal|
      %(<p>#{"<span class='warning'>POSSIBLY EXPIRED! -</span>" if deal.probably_expired?} #{link_to deal.headline, deal}</p>)
    end.join
  end

Of note is the 3rd line in the first method in the second snippet.值得注意的是第二个代码段中第一种方法的第三行。 I cannot get it to add an id to my div tag!我无法让它为我的 div 标签添加一个 id! If I change <div id='#{date.to_s}-deals'> to <div class='#{date.to_s}-deals'> it adds the class no problem but if I keep it as id= then it just creates a simple <div> tag with no attributes.如果我将<div id='#{date.to_s}-deals'>更改为<div class='#{date.to_s}-deals'>它添加类没问题,但如果我将其保留为id=那么它只创建一个没有属性的简单<div>标签。

Lest we imagine it's something to do with generating multiple divs with ids (although the ids will be different), I've also tried generating a simple <div id="thing" /> from the helper, and I get the same empty div tags as a result.以免我们认为这与生成多个带有 id 的 div 有关(尽管 id 会有所不同),我还尝试从助手生成一个简单的<div id="thing" /> ,并且得到了相同的空 div结果是标签。

WTF?跆拳道?

You have to pass a whitelist of attributes to the sanitize helper https://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize您必须将属性的白名单传递给消毒助手https://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize

To allow id attribute允许 id 属性

<%= sanitize print_grouped_deals, attributes: %w(id) %>

To set the default allowed tags or attributes across your application在整个应用程序中设置默认的允许标签或属性

# In config/application.rb
config.action_view.sanitized_allowed_tags = ['div', 'h3']
config.action_view.sanitized_allowed_attributes = ['id', 'class']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM