如何通过Asciidoctor Ruby API实现文档属性值替换
解决Asciidoctor Ruby API属性替换不生效的问题
问题原因
- 属性优先级冲突:文档头部定义的属性(如
:updated: 1 Jan 2000)优先级高于API调用中attributes参数传入的属性,导致传入的属性被忽略。 - 属性值类型问题:如果传入的
src_mtime是时间对象而非字符串,Asciidoctor无法正确解析并替换。
解决方案
1. 强制覆盖文档内的属性
如果你的文档中已经定义了:updated属性,需要用override_attributes参数强制覆盖,或者在属性名后添加!标记:
方式一:使用override_attributes参数
Asciidoctor.convert adoc, override_attributes: { updated: src_mtime.strftime('%d %b %Y') }
方式二:带!的属性名
Asciidoctor.convert adoc, attributes: { 'updated!': src_mtime.strftime('%d %b %Y') }
2. 确保属性值为字符串类型
如果文档中没有定义:updated属性,只需确保传入的属性值是字符串(时间对象需格式化)即可:
# 将时间对象格式化为可读字符串 updated_str = src_mtime.strftime('%d %b %Y') Asciidoctor.convert adoc, attributes: { updated: updated_str }
验证说明
你的Asciidoc文档中{updated}的引用格式是正确的,只要按照上述方式传递属性,就能正常替换为指定值。
内容的提问来源于stack exchange,提问作者toolforger
相关产品推荐
相关产品推荐

