You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Jekyll Liquid标签报错:Unknown tag 'endmy_tag' 求助

问题原因与解决方法

核心错误原因

你定义的MyTag继承自Liquid::Tag,这是单标签类型,不需要闭合标签{% endmy_tag %}。但你在使用时采用了块标签的写法(带闭合标签),导致Liquid无法识别endmy_tag这个未知标签。

如果需要支持带内部内容的块标签(即保留{% endmy_tag %}和中间的文本),需要修改标签类的继承关系并调整参数解析逻辑;如果不需要内部内容,直接修改使用方式即可。


方案1:改为单标签使用(无需内部内容)

直接去掉闭合标签,使用方式修改为:

{% my_tag title="hello" step="world" %}

同时注意:原标签类中render方法里的#{super}没有实际作用,因为Liquid::Tag的super不会返回内容,可以删除这部分。


方案2:改为块标签(支持内部内容)

修改my_tag.rb代码,继承Liquid::Block(块标签的基类),并正确解析参数:

# my_tag.rb
module Jekyll
  class MyTag < Liquid::Block
    def initialize(tag_name, markup, tokens)
      super
      # 解析标签参数中的键值对
      @params = {}
      markup.scan(/(\w+)\s*=\s*"([^"]+)"/) do |key, value|
        @params[key.to_sym] = value
      end
      @title = @params[:title]
      @step = @params[:step]
    end

    def render(context)
      # 获取并渲染块内部的内容
      content = super(context)
      output = "<div>"
      output += "<h1>#{@title} #{@step}</h1>"
      output += "<p>#{content}</p>"
      output += "</div>"
      output
    end
  end
end

Liquid::Template.register_tag('my_tag', Jekyll::MyTag)

此时你的原使用方式就能正常工作:

{% my_tag title="hello" step="world" %}
This is the data
{% endmy_tag %}

额外说明

  1. 原代码中@title = markup['title']是错误写法:markup是字符串类型,不能通过哈希键的方式取值,必须用正则提取参数。
  2. Liquid::Block的render方法中,super(context)会返回块内部渲染后的文本内容,这是实现块标签的关键。

内容的提问来源于stack exchange,提问作者Amit Kumar Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 00:30:00