html 在 rails 5.1 的助手中

html in helper with rails 5.1

我尝试用 rails 5.1 构建一个助手。

我需要:

 <div class="card-sleep-body-price">
    <span>à partir de</span>
       <p>45.53€</
  </div>

我尝试构建:

  def sleep_price(poi)
      if !poi.tariffs.blank?
        tag.div class: 'card-sleep-body-price' do
          <span>à partir de</span>
          <p>poi.poitable.tariffs.first.price '€'</p>
        end
      end
  end

我该如何解决?

这是一种方法。修改您的代码以使用引号和字符串插值,让 Ruby 知道什么是文字,什么是代码。

def sleep_price(poi)
  "<span>à partir de</span><p>#{poi.poitable.tariffs.first.price}€</p>"
end

但是,因为在帮助器或视图中使用长链点符号被认为是不好的形式,请考虑在模型中执行此逻辑:

class Poi < ActiveRecord::Base
  belongs_to :poitable

  def price
    self.poitable.tariffs.first.price
  end

end

从视图上看,您可以按如下方式调用此方法:

<%= sleep_price(match.sleep) %>

或者,您可以从控制器调用 match.sleep,或许可以将其设置为视图中可用的实例变量。

助手可能看起来像:

def sleep_price(price)
  "<span>à partir de</span><p>#{price}€</p>"
end

嗨,本,你可以使用 Rails content_tag 助手来构建 html 元素。

view helper

def generate_price(label:, price:, class: "element-class")

content_tag :div, class: class do

concat(content_tag(:span, label))

concat(content_tag(:p, price))

结束

结束

用法:

<%= generate_price(label: à partir de, price: 45.53€)%>

<div class="element-class"><span>à partir de</span><p>45.53€</p></div>

嵌套 content_tag:https://robots.thoughtbot.com/nesting-content-tag-in-rails-3

content_tag: https://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag

希望对您有所帮助

我认为这是一种更优雅的方式:

def sleep_price(poi)
  return if poi.tariffs.blank?

  tag.div class: "card-sleep-body-price" do
    concat(tag.span "à partir de")
    concat(tag.p "#{poi.poitable.tariffs.first.price} €")
  end
end