首页 > 解决方案 > 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应该返回每个postin的缩略图标签posts

编辑 2

当然,我应该thumb对个别帖子进行定义。我想我需要了解如何为特定页面类型定义自定义变量。

标签: jekyllliquid

解决方案


假设您只需要 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 插件的示例模板。


推荐阅读