从Jekyll插件向页面添加属性 [英] Add properties to a page from a Jekyll plugin
问题描述
说我想创建一个页面,内容如下:
Say I want to have a page with content like this:
<h1>{{page.comment_count}} Comment(s)</h1>
{% for c in page.comment_list %}
<div>
<strong>{{c.title}}</strong><br/>
{{c.content}}
</div>
{% endfor %}
默认情况下,页面上没有名为comment_count
或comment_list
的变量;相反,我希望将这些变量从Jekyll插件添加到页面.在不干扰Jekyll现有代码的情况下,我可以在哪里安全地填充这些字段?
There are no variables on the page named comment_count
or comment_list
by default; instead I want these variables to be added to the page from a Jekyll plugin. Where is a safe place I can populate those fields from without interfering with Jekyll's existing code?
还是有一种更好的方法来获得像这样的评论列表?
Or is there a better way of achieving a list of comments like this?
推荐答案
不幸的是,目前还没有可能添加这些属性而又不会弄乱Jekyll内部的东西.我们正在为#after_initialize
等添加钩子,但是还没有.
Unfortunately, there isn't presently the possibility to add these attributes without some messing with internal Jekyll stuff. We're on our way to adding hooks for #after_initialize
, etc but aren't there yet.
我最好的建议是像使用我的博客上的我的Octopress Date插件.它使用Jekyll v1.2.0的Jekyll::Post#to_liquid
方法添加这些属性,这些属性是通过Post
在Post
上收集的:
My best suggestion is to add these attributes as I've done with my Octopress Date plugin on my blog. It uses Jekyll v1.2.0's Jekyll::Post#to_liquid
method to add these attributes, which are collected via send(attr)
on the Post
:
class Jekyll::Post
def comment_count
comment_list.size
end
def comment_list
YAML.safe_load_file("_comments/#{self.id}.yml")
end
# Convert this post into a Hash for use in Liquid templates.
#
# Returns <Hash>
def to_liquid(attrs = ATTRIBUTES_FOR_LIQUID)
super(attrs + %w[
comment_count
comment_list
])
end
end
super(attrs + %w[ ... ])
将确保仍然包含所有旧属性,然后收集与String
数组中的条目相对应的方法的返回值.
super(attrs + %w[ ... ])
will ensure that all the old attributes are still included, then collect the return values of the methods corresponding to the entries in the String
array.
这是到目前为止扩展帖子和页面的最佳方法.
This is the best means of extending posts and pages so far.
这篇关于从Jekyll插件向页面添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!