I want to write a Jekyll filter, which take a list as a argument, and return a string of a list without redundent elements.
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.
When I change the input argument as string "[1,2,2,3]"
, arr
is a normal string.
Does jekyll forbid non-string argument for filter?
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).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.