Post

Jekyll 代码块展示

展示代码高亮是每个技术博客与生俱来的使命,而展示行号,也是一个不可或缺的需求。对 Jekyll 用户的好消息是,官方对此提供了友好的支持。

语法高亮

常规的 Markdown 语法:使用 ``` 或者 ~~~ 符号可以展示语法高亮代码块。另外,也可以使用 Jekyll 的 highlight tag,例如,展示一段 HTML 代码:

1
2
3
{% highlight html %}
  <p>This is some text in a paragraph.</p>
{% endhighlight %}

显示行号

有两种方式可以选择:

使用 Kramdown 配置

按这种方法可以对常规的 Markdown 的代码段自动显示行号,故为首选。启用时,在 _config.yml 中添加以下配置:

1
2
3
4
5
6
7
8
9
kramdown:
  syntax_highlighter: rouge
  syntax_highlighter_opts:   # Rouge Options › https\://github.com/jneen/rouge#full-options
    css_class: highlight
    span:
      line_numbers: false
    block:
      line_numbers: true
      start_line: 1

使用 highlight

highlight 后面声明类 linenos 也可以显示行号:

1
2
3
{% highlight html linenos %}
  <p>This is some text in a paragraph.</p>
{% endhighlight %}

特殊代码处理

Markdown 解析代码块时,如遇到 Liquid 的源码,由于转义字符 {},会使用得 Liquid 的部分不被渲染。举个例子,假设源代码是:

1
2
3
4
5
<p>
  {% if site.data.showAuthor %}
    Author: {{ site.data.author }}
  {% endif %}
</p>

那么 Jekyll 编译后的 HTML 输出结果是:

1
<p></p>

可见 Liquid 部分 {% if %}...{% endif %} 已经丢失了。为此,Jekyll 提供了两种解决方法:

  • 用标签 {% raw %}{% endraw %} 包裹转义字符:

    1
    2
    3
    4
    5
    6
    7
    
    {% raw %}
      <p>
        {% if site.data.showAuthor %}
          Author: {{ site.data.author }}
        {% endif %}
      </p>
    {% endraw %}
    
  • 作为替代,如果 Jekyll 的版本在 4.0 及以上,也可以在 post 顶部的 YAML 区域指定:

    1
    2
    3
    
    ---
    render_with_liquid: false
    ---
    

两种方法的输出都是:

1
<p>Author: Bob</p>

使用场景的考虑

无论是需要显示语法高亮还是行号,都推荐以配置 kramdown 选项的方式去实现,毕竟效率第一。当然了,如果你是重度编码癖坚持要敲完一大串词组 {% raw %}{% highlight %}...{% endhighlight %}{% endraw %},那么请随意享受宪法赋予你的自由。

参考

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.