Jekyll Liquid阅读时长统计排除代码块及代码行数统计方案咨询
实现方案分两种,可根据你的部署环境选择:
方案1:纯Liquid模板实现(适配GitHub Pages默认环境,无需安装插件)
直接在模板中添加以下逻辑处理内容:
{% assign content_without_code = post.content %} {% assign code_line_count = 0 %} <!-- 处理```包裹的Markdown代码块 --> {% assign code_blocks = content_without_code | split: "```" %} {% for block in code_blocks %} {% if forloop.index is even %} {% assign lines = block | newline_to_br | split: "<br />" | size %} {% assign code_line_count = code_line_count | plus: lines %} {% else %} {% if forloop.first %} {% assign temp_content = block %} {% else %} {% assign temp_content = temp_content | append: block %} {% endif %} {% endif %} {% endfor %} {% assign content_without_code = temp_content %} <!-- 处理<pre><code>包裹的HTML代码块 --> {% assign code_blocks = content_without_code | split: "<pre><code>" %} {% assign temp_content = "" %} {% for block in code_blocks %} {% if forloop.index == 1 %} {% assign temp_content = block %} {% else %} {% assign code_end = block | split: "</code></pre>" %} {% assign lines = code_end[0] | newline_to_br | split: "<br />" | size %} {% assign code_line_count = code_line_count | plus: lines %} {% assign temp_content = temp_content | append: code_end[1] %} {% endif %} {% endfor %} {% assign content_without_code = temp_content %} <!-- 计算阅读时长,不足1分钟按1分钟算 --> {% assign word_count = content_without_code | strip_html | number_of_words %} {% assign read_time = word_count | divided_by: 180 %} {% if read_time < 1 %} {% assign read_time = 1 %} {% endif %}
处理完成后直接输出结果即可:
<span class="post-meta"> {{ read_time }} min read and {{ code_line_count }} lines of code </span>
注意:如果需要排除代码块开头的语言标记行(比如```js的js那行),可以在统计行数的时候减1即可。
方案2:自定义Jekyll插件实现(性能更高、边界情况处理更完善)
在博客根目录的_plugins文件夹下新建reading_time.rb文件,写入以下代码:
module Jekyll module ReadingTimeFilter # 计算排除代码块后的阅读时长 def read_time_without_code(content) # 移除两种格式的代码块 content = content.gsub(/```.*?```/m, '') content = content.gsub(/<pre><code>.*?<\/code><\/pre>/m, '') word_count = content.strip_html.split.size # 不足1分钟按1分钟算 [word_count / 180, 1].max end # 统计所有代码块的总行数 def count_code_lines(content) line_count = 0 # 统计Markdown代码块行数 content.scan(/```(.*?)```/m).each { |code| line_count += code[0].lines.count } # 统计HTML代码块行数 content.scan(/<pre><code>(.*?)<\/code><\/pre>/m).each { |code| line_count += code[0].lines.count } line_count end end end Liquid::Template.register_filter(Jekyll::ReadingTimeFilter)
之后直接在模板中调用自定义过滤器即可:
<span class="post-meta"> {{ post.content | read_time_without_code }} min read and {{ post.content | count_code_lines }} lines of code </span>
注意:该方案无法在GitHub Pages默认部署环境下使用,如需部署到GitHub Pages需要配置GitHub Actions自行构建站点。
内容的提问来源于stack exchange,提问作者mostsignificant
相关产品推荐
相关产品推荐

