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

Jekyll中含Liquid标签的Markdown表格无法正常渲染问题

Jekyll自定义Liquid标签导致Markdown表格无法渲染的解决办法

问题原因

Jekyll的处理顺序是先解析Liquid标签,再渲染Markdown。当自定义Liquid标签返回<span>这类HTML内容时,Markdown解析器会将包含该HTML的表格行判定为HTML块,停止解析该行的表格语法,最终整个表格被当作纯文本包裹在<p>标签中。

解决方案

方案1:用Jekyll钩子在Markdown渲染后替换实体(推荐)

先让Markdown正常解析表格,再统一替换实体标记为目标HTML,完全避免打断Markdown解析流程:

  1. 替换实体标记:把.md文件里的{% ent X %}改成自定义文本标记,比如[[X]](避开Liquid语法冲突)。
  2. 编写钩子插件:替换原来的自定义标签代码,在_plugins/entity_handler.rb中写入:
module Jekyll
  class EntityReplacementHook < Jekyll::Generator
    priority :low # 确保在Markdown渲染完成后执行

    def generate(site)
      # 加载实体字典
      @@dictionary ||= {}
      file_path = File.join(site.source, "./assets/definitions/entities.txt")
      if File.exist?(file_path)
        File.readlines(file_path).each do |s|
          # split(2)避免实体值里包含|的情况
          key, value = s.split("|", 2)
          next if key.nil? || value.nil?
          @@dictionary[key.strip] = value.strip
        end
      end

      # 遍历所有页面和帖子替换实体
      site.pages.each { |page| replace_entities(page) }
      site.posts.docs.each { |post| replace_entities(post) }
    end

    private

    def replace_entities(document)
      return unless document.output.present?

      document.output = document.output.gsub(/\[\[(\w+)\]\]/) do |match|
        key = Regexp.last_match(1)
        @@dictionary.key?(key) ? @@dictionary[key] : "<span class='btn-false'>ERROR: entity not found</span>"
      end
    end
  end
end
  1. 修改Markdown表格:
| Cell one | Cell two |
| --- | --- |
| Cell three | [[X]] |

这样Markdown会先渲染成完整的<table>,之后钩子再把[[X]]替换为对应的<span>元素。

方案2:修改Liquid标签返回纯文本,手动添加HTML样式

如果坚持用Liquid标签,可让标签返回纯文本,再手动给单元格内容套<span>:

  1. 修改自定义标签代码:
module Jekyll
  class EntityHandler < Liquid::Tag
    @@dictionary = {}
    file = File.open("./assets/definitions/entities.txt")
    strings = file.readlines
    strings.each do |s|
      key, value = s.split("|", 2)
      @@dictionary[key.strip] = value.strip
    end
    file.close

    def initialize(name, input, tokens)
      super
      @input = input.strip
    end

    def render(context)
      dictionary = @@dictionary
      dictionary.has_key?(@input) ? dictionary[@input] : "ERROR: entity not found"
    end
  end
end

Liquid::Template.register_tag('ent', Jekyll::EntityHandler)
  1. 调整Markdown表格:
| Cell one | Cell two |
| --- | --- |
| Cell three | <span>{% ent X %}</span> |

Liquid先替换标签为纯文本,Markdown解析器会正确识别表格结构,同时保留<span>标签。

额外优化点

  • 原代码中fetch_values返回数组,改为直接取dictionary[@input]可避免输出多余的数组符号。
  • 用split("|", 2)分割实体文件行,防止实体值包含|导致分割错误。

内容的提问来源于stack exchange,提问作者Рауль Каримов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:40:38