简体   繁体   English

Jekyll用于Ruby数组的液体过滤器

[英]Liquid filter for Ruby arrays with Jekyll

I want to write a Jekyll filter, which take a list as a argument, and return a string of a list without redundent elements. 我想编写一个Jekyll过滤器,该过滤器将列表作为参数,并返回没有冗余元素的列表字符串。

My filter code is: 我的过滤器代码是:

module Jekyll
    module ArrayToSet
        def array_to_set_string(arr)
            arr.uniq.to_s
        end
    end
end

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

The usage code is 用法代码是

{{ [1,2,2,3] | array_to_set_string }}

But the complilation jekyll build failed, because the arr in the function is nul. 但是编译jekyll jekyll build失败,因为函数中的arr为nul。

When I change the input argument as string "[1,2,2,3]" , arr is a normal string. 当我将输入参数更改为字符串"[1,2,2,3]"arr是正常字符串。

Does jekyll forbid non-string argument for filter? jekyll是否禁止将非字符串参数用作过滤器?

Liquid doesn't accept Ruby code like that, but it can work with Ruby objects once they have been created by some other means (a filter or a tag). Liquid不接受这样的Ruby代码,但是一旦通过其他方式(过滤器或标签)创建了Ruby对象,它就可以使用Ruby对象。

So either make a method that creates an array, or accept strings and convert them to arrays before processing. 因此,要么创建一个创建数组的方法,要么接受字符串并在处理之前将其转换为数组。

Example of using a two-step process to create an array and then process: 使用两步过程创建数组然后进行处理的示例:

module Filter
  def to_array(str)
    str.split(',')
  end

  def uniq(arr)
    arr.uniq
  end
end

>> {{ '1,2,2,3' | to_array | uniq }}
1 2 3

You could also roll it all into one method of course: 您当然也可以将其全部滚动为一种方法:

module Filter
  def to_array_uniq(str)
    str.split(',').uniq
  end
end

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

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