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

Jekyll+Liquid中用YAML前置变量引用页面专属数据文件问题

解决Jekyll通过page.comment_id关联对应JSON数据的问题

核心原因

page.comment_id在页面YAML前置区定义的是数值类型,但Jekyll读取_data/comments-gh下的文件时,会把文件名(如76.json)作为字符串类型的键存入site.data.comments-gh。直接用数值类型的page.comment_id作为键访问,会因类型不匹配无法找到对应数据。

正确实现代码

先将page.comment_id转换为字符串,再通过方括号语法访问对应JSON数据:

{% assign comment_id_str = page.comment_id | to_s %}
{% assign comments = site.data.comments-gh[comment_id_str] %}

{% if comments %}
  {% for comment in comments %}
    <!-- 这里写你的评论处理代码 -->
  {% endfor %}
{% else %}
  <!-- 没有对应评论时的提示 -->
{% endif %}

额外注意事项

  • 如果你的JSON文件结构是包含items数组的对象(比如{"items": [/* 评论列表 */]}),再添加.items:
    {% assign comments = site.data.comments-gh[comment_id_str].items %}
    
  • 可以通过以下代码排查键的类型和数据结构:
    <!-- 输出所有comments-gh的键,确认是字符串形式 -->
    {{ site.data.comments-gh | inspect }}
    <!-- 输出转换后的comment_id字符串 -->
    {{ comment_id_str | inspect }}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 02:23:15