本週末我一直在使用Liquid模板引擎,我不知道以下是否可能。將變量傳遞給Liquid模板中的模型實例方法
假設我在Blog
模型中有方法,我可以傳遞一個整數來得到最新的N個帖子。是否可以在液體模板中使用該方法?
例如:
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
在上面的簡單的例子,在我的液體模板,我可以使用blog.all_posts
和blog.last_post
,但不知道我會怎麼做類似的東西blog.latest_posts: 10
。
任何人都可以指出我的方向是正確的嗎?
我想到的一個想法是創建一個Liquid過濾器,並將Blog對象和一個整數傳遞給它。喜歡的東西:
{% for post in blog | latest_posts(10) %}
- ,但還沒有試過,但因爲覺得我在黑暗中刺傷位左右。希望得到更多有經驗的Liquid用戶的幫助。
感謝您對before_method的信息。我同意這有點冒險,但請記住Liquid的重點是模板,而不是模板背後的機制。其目的是讓其他人可以僅使用模板語言以安全的方式製作有用/複雜的數據視圖。我認爲它非常好 - 我的客戶和他們的承包商都使用Liquid模板和我的SAAS數據。 – 2010-08-31 17:53:02