I've been playing around with the Liquid templating engine this weekend, and I wonder if the following is possible.
Say I have a latest_posts
method in a Blog
model, which I can pass an integer to to get the latest N posts. Is it possible to use that method in a liquid template?
For example:
class Blog
has_many :posts
def latest_posts(n)
posts.latest(n) # using a named scope
end
def to_liquid(*args)
{
'all_posts' => posts.all, # allows me to use {% for posts in blog.all_posts %}
'last_post' => post.last, # allows me to use {% assign recent = blog.last_post %}
'latest_posts' => posts.latest_posts(args[0]) # how do I pass variables to this?
}
end
end
In the simplified example above, in my liquid templates I can use blog.all_posts
and blog.last_post
, but have no idea how I would do anything like blog.latest_posts: 10
.
Can anyone point my in the right direction?
One idea I thought of was to create a Liquid filter and pass both the Blog object and an integer to that. Something like:
{% for post in blog | latest_posts(10) %}
- but haven't tried that yet as feel like I'm stabbing around in the dark a bit. Would appreciate some help from more experienced Liquid users.