jekyll-include-cache并不是你的Jekyll理想型缓存插件

🕘
⏱️
👁️ * 阅读

你以为 jekyll-include-cache 是给每个页面缓存,其实他只是给 include 文件做“快照”缓存,与想象有着较大偏差。

因为Jekyll构建太慢,AI Chat 推荐使用 jekyll-include-cache 插件,避免 include 文件反复渲染拖慢构建速度。

改完后发布后没发现问题,后面用不常用浏览器访问发现页面有点不大对,例如:所有页面的边栏没了、定制的大屏页面变小屏还布局错乱,开始以为是浏览器兼容性问题。后面发现标题输出的内容都变成一样了,使用常用浏览器访问排除了是样式兼容性的问题,这个窟窿点大,最开始没找到原因,AI Chat 也只是“带你去更遥远的地方”,后来一次次提交查看对比,突然想起将 include 改成 include_cached 的操作,后来撤回后全都正常了。因为站点很多 include 文件使用许多判断逻辑、变量,使用 include_cached 一切变得“静态化”了,所有页面都是用相同的标题,定制页面没有使用定制样式也使用相同样式。

下面结合实际情况简化,做个实例分析,了解下 jekyll-include-cache 的运作机制:

假设你的Jekyll所有站点都是使用了 default.html 这个布局(layout: default),在 default.html 中你引入了 _includes/title.html 和 _includes/css.html 文件,分别是:

_layouts/default.html

1
2
{% include title.html -%}
{% include css.html -%}

_includes/title.html

得到的结果:根据页面,最终输出的<title>会不一样。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{%- include happylife/page_css.html -%}
{% if page.site_title %}
<title>{{ page.title }}{% if page.parent %} - {{ page.parent }}{% endif %} - {{ page.site_title }}</title>
{% seo title=false %}
{% elsif page.site_title == false %}
<title>{{ page.title }}{% if page.parent %} - {{ page.parent }}{% endif %}</title>
{% seo title=false %}
{% else %}
    {% seo %}
{% endif %}

_includes/css.html

得到的结果:showcase页面,会植入showcase.scss文件中的样式。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{%- assign showcase = "scss/showcase.scss" -%}

{%- capture showcase %}
  {% include {{ showcase }} %}
{% endcapture -%}
{%- case page.url %}
  {%- when "/showcase/" %}
    <style>
        {{ showcase | scssify }}
    </style>
  {%- else -%}
{%- endcase -%}

将 include 改成 include_cached 后,Jekyll构建时会存下有使用到 title.html 和 css.html 的第一个页面,然后会缓存这2个 include 的渲染结果,后面再渲染其他页面有用到 title.html 和 css.html 时直接使用刚刚缓存的内容。假设第一个页面的标题是首页,那其他用了title.html 的页面渲染出来的标题也都是首页。

_layouts/default.html

1
2
{% include_cached title.html -%}
{% include_cached css.html -%}

最后所有使用 title.html 和 css.html 的页面得到的结果变成了

1
<title>首页</title>

最开始看到这个结果有点被颠覆的感觉,相比 DedeCMS、Wordpress、Typecho而言,jekyll-include-cache完全跌破预期,那么jekyll-include-cache和include_cached还能用吗?

答案肯定是可以。

官方的案例中有通过外部传入数据的方法,但未提供传入变量的方法,不确定是否可行。

外部文件

1
{% include_cached shirt.html size=medium color=red %}

include 文件

1
Buy our {{ include.color }} shirt in {{ include.size }}!

推荐用在没有逻辑判断、没有变量的 include 文件上。

转载请注明转自:一极乐https://yijile.com/zh/defects-in-jekyll-include-cache/

CC BY-NC-SA 4.0 声明
本文采用 CC BY-NC-SA 4.0方式授权。
转载请注明出处和本文链接,说明是否进行修改,不得用于商业用途,使用相同方式共享。

最后更新于 |
一极乐 赏荷