如何修改Jekyll AsciiDoc HTML生成器模板并注入自定义变量
问题
我正在使用AsciiDoc和Jekyll生成静态站点,基于单个HTML模板,希望在模板中注入一个定义在项目属性中的变量。
当前HTML模板代码如下:
{% assign timestamp = site.time | date: '%s' %} {% assign my_project_value = attributes.my_project_value %} <script> const timestamp = '{{timestamp}}'; const my_project_value = '{{my_project_value}}'; </script>
其中timestamp能被正确填充,但my_project_value始终为空。而从配置输出可以看到该变量已存在:
puts "Config: " + config.to_s Config: {"page_ext"=>"", "title"=>"Page title", "asciidoctor"=>{"attributes"=>{"attribute-missing"=>"warn", ..., "my_project_value"=>"SomeProjectValue", "page_ext"=>"", "figure-caption!"=>"", "html"=>"", "title-break"=>""}}, ...}
我还尝试过以下写法,同样返回空值:
<script> const my_project_value = '{{ site.asciidoctor.attributes.my_project_value }}'; </script>
请问如何修改HTML模板注入自定义值?正确语法是什么?
解决方案
1. 正确访问Asciidoctor属性的路径
Jekyll中访问Asciidoctor配置属性的正确路径是site.asciidoctor.attributes,之前的写法问题可能出在配置读取的层级或模板解析时机。
2. 修正后的模板代码
直接使用完整路径读取属性,同时添加转义处理避免字符冲突:
{% assign timestamp = site.time | date: '%s' %} {% assign my_project_value = site.asciidoctor.attributes.my_project_value %} <script> const timestamp = '{{ timestamp }}'; const my_project_value = '{{ my_project_value | escape }}'; </script>
3. 备选方案:通过页面Front Matter中转
如果直接读取配置仍有问题,可以在页面的Front Matter中显式传递属性:
--- my_project_value: "{{ site.asciidoctor.attributes.my_project_value }}" ---
之后在模板中通过page对象访问:
const my_project_value = '{{ page.my_project_value | escape }}';
4. 调试验证方法
可以在模板中临时输出完整的属性结构,确认目标变量是否可被模板解析:
<pre>{{ site.asciidoctor.attributes | inspect }}</pre>
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

