首页 > 解决方案 > 如何在 show.html.erb 中显示液体内容?

问题描述

我正在开发 Rails 5 中的应用程序,我的目标是使用液体在页面显示页面上显示产品。

页面.rb

def to_liquid
  Product.all
end

产品.rb

belongs_to :category
def to_liquid
  {  'name' => self.name,
      'price' => self.price,
      'description' => self.description,
      'category' => self.category
  }
end

类别.rb

has_many :products

  def to_liquid
  {  'name' => self.name}
  end

show.html.erb(页面)

<%= RedCloth.new(Liquid::Template.parse(@page.content).render('page' => @page)).to_html %>

_form.html.erb(页面)

<%= form_with(model: page, local: true) do |form| %>
  <% if page.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(page.errors.count, "error") %> prohibited this page from being saved:</h2>

      <ul>
      <% page.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>

  <div class="field">
    <%= form.label :content %>
    <%= form.text_area :content %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

如果我添加以下文本,则在内容的文本区域中

Test for liquid in rails
{% for product in page.products %}
*{{ product.name }}* {{ product.price }}
Category: {{ product.category.name }}
{% endfor %}

在显示页面上仅显示“测试导轨中的液体”,但未显示产品。请帮我弄清楚我哪里出错了我对液体完全陌生。

我没有定义 to_liquid,而是在模型中使用了liquid_methods,但是我得到了一个错误未定义的方法`liquid_methods,所以我在stackoverflow上找到了定义to_liquid。我正在关注一个教程http://railscasts.com/episodes/118-liquid?autoplay=true

标签: ruby-on-railsshopifyliquid

解决方案


推荐阅读