Jekyll中含Liquid标签的Markdown表格无法正常渲染问题
Jekyll自定义Liquid标签导致Markdown表格无法渲染的解决办法
问题原因
Jekyll的处理顺序是先解析Liquid标签,再渲染Markdown。当自定义Liquid标签返回<span>这类HTML内容时,Markdown解析器会将包含该HTML的表格行判定为HTML块,停止解析该行的表格语法,最终整个表格被当作纯文本包裹在<p>标签中。
解决方案
方案1:用Jekyll钩子在Markdown渲染后替换实体(推荐)
先让Markdown正常解析表格,再统一替换实体标记为目标HTML,完全避免打断Markdown解析流程:
- 替换实体标记:把.md文件里的
{% ent X %}改成自定义文本标记,比如[[X]](避开Liquid语法冲突)。 - 编写钩子插件:替换原来的自定义标签代码,在
_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
- 修改Markdown表格:
| Cell one | Cell two | | --- | --- | | Cell three | [[X]] |
这样Markdown会先渲染成完整的<table>,之后钩子再把[[X]]替换为对应的<span>元素。
方案2:修改Liquid标签返回纯文本,手动添加HTML样式
如果坚持用Liquid标签,可让标签返回纯文本,再手动给单元格内容套<span>:
- 修改自定义标签代码:
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)
- 调整Markdown表格:
| Cell one | Cell two | | --- | --- | | Cell three | <span>{% ent X %}</span> |
Liquid先替换标签为纯文本,Markdown解析器会正确识别表格结构,同时保留<span>标签。
额外优化点
- 原代码中
fetch_values返回数组,改为直接取dictionary[@input]可避免输出多余的数组符号。 - 用
split("|", 2)分割实体文件行,防止实体值包含|导致分割错误。
内容的提问来源于stack exchange,提问作者Рауль Каримов
相关产品推荐
相关产品推荐

