【问题标题】:How to iterate through an Rails 6 object in a liquid template如何在液体模板中迭代 Rails 6 对象
【发布时间】:2020-09-25 22:07:05
【问题描述】:

我需要遍历液体模板中的 rails 6 对象。使用 drop 类传递单个对象可以正常工作(在没有最新文档的情况下设置所有内容是一种相当老套的方法,但它最终可以工作)。在我的控制器中,我将一个对象传递给这样的放置类:

@template.assigns['object'] = Drops::ObjectsDrop.new(@object)

但是现在让我们说对象有许多可以通过 @object.items 访问的项目。每个项目都有一个名称和描述。如果我理解正确,我也需要物品的掉落类。但是像这样将整个数组传递给 drop 类是行不通的:

module Drops

  class ItemsDrop < Liquid::Drop

    def initialize(items)
      @items = items
    end

    def item_name
      @items.each do |item|
        @item["item_name"]
      end
    end
...
...
  end
end

如何将所有 @object.items 传递给 item-drop-class 以便稍后在液体 for 循环中迭代每个项目?

【问题讨论】:

    标签: ruby-on-rails liquid


    【解决方案1】:

    终于成功了:

    @item_assigns = @object_items.collect {|x| x.to_drop}
    @template.assigns['items'] = @items_assigns
    

    以及模型中的以下to_drop方法:

      def to_drop
        Drops::ImagesDrop.new self
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 2014-10-18
      • 1970-01-01
      相关资源
      最近更新 更多