jekyll - Jekyll/Liquid:如何将帖子前端内容传递给自定义标签?
问题描述
我正在关注构建自定义液体标签的演示。
我想创建一个标签,该标签采用给定帖子的图像并返回一个图像标签及其等效缩略图的路径。
假设一个帖子的frontmatter看起来像这样:
---
title: Build a plugin
layout: post
image: plugin.jpg
---
我的标签看起来像这样:
{% thumb_for post.image %}
所需的输出将是:
<img src="https://example.com/images/thumbs/plugin.jpg">
到目前为止,我的尝试如下所示:
module Jekyll
class RenderThumbTag < Liquid::Tag
def initialize(tag_name, image, tokens)
super
@image = image
end
def render(context)
"<img src='#{context["site"]["url"]}/images/thumbs/#{@image}'>"
end
end
end
Liquid::Template.register_tag('thumb_for', Jekyll::RenderThumbTag)
但是,呈现的标签最终为http://example.com/images/thumbs/post.image
. 显然我想post.image
评估文件名。我需要采取哪些步骤?(还是我把 Liquid 弄错了?)
编辑
我意识到我的主要问题是我不知道如何在这个posts
循环中引用当前迭代:
{% for post in site.posts %}
<li class="post">
{% thumb_for %}
</li>
{% endfor %}
thumb_for
应该返回每个post
in的缩略图标签posts
。
编辑 2
当然,我应该thumb
对个别帖子进行定义。我想我需要了解如何为特定页面类型定义自定义变量。
解决方案
假设您只需要 front matter 变量,并且自定义标签的任何参数都将被忽略,这应该可以完成工作:
module Jekyll
class RenderThumbTag < Liquid::Tag
def render(context)
page = context.registers[:page]
"<img src='/images/thumbs/#{page.image}'>"
end
end
end
Liquid::Template.register_tag('thumb_for', Jekyll::RenderThumbTag)
你会像这样调用标签:
{% thumb_for %}
顺便说一句,我在我的博客上提供了 Jekyll 插件的示例模板。
推荐阅读
- arrays - 如何在Ruby中的每个第n个字符之后有效地分割一个很长(数百万个字符)的字符串?
- time-series - Warpscript:操作计数超过最大值 100000
- c - 在函数内逐行读取和检查系统调用
- c# - 如何以编程方式将控件添加到 Windows UWP UserControl?
- kubernetes - 通过 operator-sdk/client-go 中的 taints 列出不可调度的 kubernetes 节点
- c# - 如何将过滤、排序、分组和分页等网格操作传递给 Web API 服务?
- qt - 在win-10中部署的qt-designer项目在win-7中不起作用
- android - 为什么我的 ImageView 使用 ConstraintLayout 得到 1 个像素的高度?
- sql-server - 由于跌落限制,Flyway clean 无法清洁
- python - 在字符分隔符上将字符串(对象)拆分为两列,但保留字符分隔符