【问题标题】:Concatenate arrays in liquid在液体中连接数组
【发布时间】:2017-03-07 16:57:35
【问题描述】:

我试图在 Liquid/jekyll 中连接三个数组,但在最终数组(出版物)中,我只得到第一个数组的元素(论文)

{% assign papers = (site.publications | where:"type","paper" | sort: 'date') | reverse %}
{% assign posters = (site.publications | where:"type","poster" | sort: 'date') | reverse %}
{% assign abstracts = (site.publications | where:"type","abstract" | sort: 'date') | reverse %}
{% assign publications = papers | concat: posters | concat: abstracts %}

我错过了什么?

【问题讨论】:

  • 您确定postersabstracts 是非空数组吗?通过将它们分别输出到页面来仔细检查。
  • 什么是{{ pagers | inspect }}{{ posters | inspect }} 输出。
  • @KevinWorkman。我已经仔细检查过了。如果我分别循环并输出每个数组,所有元素都在那里
  • @DavidJacquel 和寻呼机我猜你的意思是论文。两个输出如下所示: [{ "path": "_publications/poster2016.markdown", "id": "/publications/poster2016", "output": "", "content": "", "relative_path": " _publications/poster2016.markdown", "url": "/publications/poster2016.html", "collection": "publications", "excerpt": "", "previous": { "path": "_publications/mb2016.markdown ","id":"/publications/mb2016","输出":"","内容":"","relative_path":"_publications/mb2016.markdown","url":"/publications/mb2016.html ", "收藏": "出版物", "摘录":..........
  • 最好用这个输出更新你的问题,然后你可以很好地格式化它。 ;-)

标签: jekyll liquid


【解决方案1】:

新答案

Jekyll 现在使用 Liquid 4.x。所以我们可以使用concat 过滤器!

旧答案

concat 过滤器不是 jekyll 3.2.1 使用的当前液体 gem (3.0.6) 的一部分。

它只能在液体 4 (https://github.com/Shopify/liquid/blob/v4.0.0.rc3/lib/liquid/standardfilters.rb#L218) 中使用。

我可能会参加 Jekyll 4。

与此同时,这个插件可以完成这项工作:

=begin
  Jekyll filter to concatenate arrays
  Usage:
    {% assign result = array-1 | concatArray: array-2 %}
=end
module Jekyll
  module ConcatArrays

    # copied from https://github.com/Shopify/liquid/blob/v4.0.0.rc3/lib/liquid/standardfilters.rb
    def concat(input, array)
      unless array.respond_to?(:to_ary)
        raise ArgumentError.new("concat filter requires an array argument")
      end
      InputIterator.new(input).concat(array)
    end

   class InputIterator
      include Enumerable

      def initialize(input)
        @input = if input.is_a?(Array)
          input.flatten
        elsif input.is_a?(Hash)
          [input]
        elsif input.is_a?(Enumerable)
          input
        else
          Array(input)
        end
      end

      def concat(args)
        to_a.concat(args)
      end

      def each
        @input.each do |e|
          yield(e.respond_to?(:to_liquid) ? e.to_liquid : e)
        end
      end
    end

  end
end

Liquid::Template.register_filter(Jekyll::ConcatArrays)

【讨论】:

  • 谢谢,我从这里 (jekyllrb.com/docs/plugins) 按照方法 1 安装了插件,效果很好。
  • 好消息:现在这是 Jekyll 的一部分(当前版本 3.5.2 使用 Liquid 4.0.0)
猜你喜欢
  • 1970-01-01
  • 2022-07-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多