Reputation: 872
I spent today trying to do something simple with Jekyll for http://bitcoin.org/clients.html
We have a list of Bitcoin software, and every so often that page gets regenerated. It would be good if the order of clients would be randomised for equal exposure.
{% random page.clients %}
{% for client in page.clients %}
...
I'm sure it's simple:
class Random < Liquid::Tag
def initialize(tag_name, collection_name, tokens)
@collection_name = collection_name.to_s
super
end
def render(context)
collection = context[@collection_name]
collection = collection.sort_by{rand}
context[@collection_name] = collection
super
end
end
Liquid::Template.register_tag('random', Random)
Why doesn't it work? I see absolutely no change.
I assume I am not assigning to page.clients correctly, because if I try:
context[:foo] = collection
{% random page.clients %}
{% for client in page.clients %}
...
Then I get a blank page. But printing @collection_name shows "page.clients"...
Any ideas?
Thanks
Upvotes: 3
Views: 1973
Reputation: 1647
This can now be achieved with the Jekyll "sample" filter..
For example, to random get 3 posts...
{% assign posts = site.posts | sample:3 %}
{% for post in posts %}
...
{% endfor %}
Upvotes: 3
Reputation: 872
class Random < Liquid::Tag
Syntax = /(\w+[.]?\w+)\s+(\w+)/o
def initialize(tag_name, markup, tokens)
if markup =~ Syntax
@collection_name = $1
@randomized_name = $2
else
raise SyntaxError.new("Syntax Error in 'random' - Valid syntax: random [source] [var]")
end
super
end
def render(context)
collection = context[@collection_name]
collection = collection.sort_by{rand}
context[@randomized_name] = collection
return
end
end
Liquid::Template.register_tag('random', Random)
And:
{% random page.clients clients %}
{% for client in clients %}
...
Upvotes: 3