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

如何在Jekyll中实现带参数和多行文本的自定义引用短代码?

Jekyll实现自定义引用短代码的最优方案

问题描述

想要在Jekyll中实现类似短代码的引用块功能,期望的使用形式如下:

{% quote author="My Author" %}
This is the quoted content
spanning multiple lines

And paragraphs
{% endquote %}

同时有两个疑问:

  • 实现该功能的最优方式是什么?
  • Jekyll标签插件是否无法传入多个参数?

此前已研究过HTML Includes和Custom Tags两种替代方案,但均存在局限性,也了解到通过字符串拼接或JSON传递多属性的方法。

现有方案的局限性

HTML Includes的局限性

通过捕获内容作为参数实现,需先创建_includes/quote.html文件:

<blockquote>
    {{ include.quote | markdownify }}
    <p><em>{{ include.author }}</em></p>
</blockquote>

在博客文章中的使用方式:

{% capture quote %}
This is the quote content
spanning multiple lines

And paragraphs
{% endcapture %}
{% include quote.html quote=quote author="My Author" %}

该方案可正常运行,但撰写时需先通过capture捕获内容,使用体验繁琐。

Custom Tags的局限性

官方文档仅展示了两种基础使用形式:

  • 无闭合标签的形式:{% render_time 页面渲染于: %}
  • 带闭合标签的形式:
{% render_time %}
页面渲染于:
{% endrender_time %}

示例未涉及多参数传递的场景,容易造成“无法传多参数”的误解。

最优实现方案:自定义Liquid标签插件

Jekyll的自定义标签插件完全支持传入多个参数,以下是实现你期望的quote短代码的具体步骤:

1. 创建标签插件文件

在项目根目录下新建_plugins文件夹(若已存在则跳过),在其中创建quote_tag.rb文件,代码如下:

module Jekyll
  class QuoteTag < Liquid::Block
    def initialize(tag_name, markup, tokens)
      super
      # 解析传入的键值对参数,比如author="My Author"
      @attributes = {}
      markup.scan(/(\w+)\s*=\s*"([^"]+)"/) do |key, value|
        @attributes[key.to_sym] = value
      end
    end

    def render(context)
      # 获取标签包裹的内容,转译为Markdown格式
      raw_content = super.strip
      rendered_content = Liquid::Template.parse(raw_content).render(context)
      markdown_content = context.registers[:site].find_converter_instance(Jekyll::Converters::Markdown).convert(rendered_content)

      # 生成最终HTML结构
      html = %(<blockquote class="custom-quote">)
      html += markdown_content
      if @attributes[:author]
        html += %(<p class="quote-author">— #{@attributes[:author]}</p>)
      end
      html += %(</blockquote>)
      html
    end
  end
end

Liquid::Template.register_tag('quote', Jekyll::QuoteTag)

2. 添加自定义样式(可选)

在项目的CSS文件中添加样式,优化引用块的视觉效果:

.custom-quote {
  border-left: 4px solid #2c3e50;
  padding-left: 1rem;
  margin: 1.5rem 0;
  font-style: italic;
  color: #34495e;
}

.quote-author {
  text-align: right;
  margin-top: 0.5rem;
  font-style: normal;
  font-weight: 600;
}

3. 在文章中直接使用

按照你最初期望的形式调用即可:

{% quote author="My Author" %}
This is the quoted content
spanning multiple lines

And paragraphs
{% endquote %}

关于多参数传递的说明

自定义标签插件可通过正则解析标记(markup)中的多个参数,若需要扩展支持source="某书籍"等额外参数,只需在initialize方法的正则解析逻辑中保留现有代码,再在render方法中添加对应的HTML输出即可。

你提到的字符串拼接或JSON传递多属性的方法也可行,但正则解析键值对的方式更直观,更符合短代码的使用习惯。


内容的提问来源于stack exchange,提问作者aufziehvogel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:11:07