ruby – 将变量传递给Liquid模板中的模型实例方法
发布时间:2020-12-16 21:39:37 所属栏目:百科 来源:网络整理
导读:本周末我一直在玩液体模板引擎,我想知道以下是否可行. 假设我在Blog模型中有一个latest_posts方法,我可以传递一个整数来获取最新的N个帖子.是否可以在液体模板中使用该方法? 例如: class Blog has_many :posts def latest_posts(n) posts.latest(n) # usin
本周末我一直在玩液体模板引擎,我想知道以下是否可行.
假设我在Blog模型中有一个latest_posts方法,我可以传递一个整数来获取最新的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用户提供的一些帮助. 解决方法
在这里回答我自己的问题,我找到了
Liquid groups pages中记录的解决方案.
基本上,我需要为最新的帖子创建一个drop – 一个LatestPostsDrop – 并且使用before_method方法将变量传递给它.这是完整的解决方案: class Blog has_many :posts def latest_posts LatestPostsDrop.new(posts) end def to_liquid { 'all_posts' => posts.all,'last_post' => post.last,'latest_posts' => latest_posts } end end class LatestPostsDrop < Liquid::Drop def initialize(posts) @posts = posts end def before_method(num) @posts.latest(num) # Post.latest is a named scope end end 执行上述操作后,您可以使用以下内容迭代任意数量的最新帖子: {% for post in blog.latest_posts.10 %} # the last attribute can be any integer <p>{{ post.title }}</p> {% endfor %} 它似乎有点hacky,但它的工作:) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |