在yaml中使用占位符

Tra*_*ace 26 yaml indirection computed-properties template-variables

有没有办法在yaml中使用占位符,如下所示:

foo: &FOO
    <<propname>>: 
        type: number 
        default: <<default>>

bar:
    - *FOO 
       propname: "some_prop"
       default: "some default" 
Run Code Online (Sandbox Code Playgroud)

dre*_*mac 66

上下文

  • YAML版本1.2
  • 用户希望在YAML中包含可变占位符

问题

  • YAML本身不支持变量占位符
  • Anchors和Aliases确实允许某种程度的抽象和间接,但是它们不能作为可以插入整个YAML文本中的任意区域的变量占位符.它们必须作为单独的YAML节点放置
  • 有一些附加库支持任意变量占位符,但它们不是本机YAML规范的一部分

请考虑以下示例YAML.它是格式良好的YAML语法,但它使用带有嵌入式表达式的(非标准)大括号占位符.

嵌入式表达式不会在YAML中产生所需的结果,因为它们不是本机YAML规范的一部分.尽管如此,它们仅用于本示例中,以帮助说明标准YAML可用的内容以及不适用的内容.

part01_customer_info:
  cust_fname:   "Homer"
  cust_lname:   "Himpson"
  cust_motto:   "I love donuts!"
  cust_email:   homer@himpson.org

part01_government_info:
  govt_sales_taxrate: 1.15

part01_purchase_info:
  prch_unit_label:    "Bacon-Wrapped Fancy Glazed Donut"
  prch_unit_price:    3.00
  prch_unit_quant:    7
  prch_product_cost:  "{{prch_unit_price * prch_unit_quant}}"
  prch_total_cost:    "{{prch_product_cost * govt_sales_taxrate}}"

part02_shipping_info:
  cust_fname:   "{{cust_fname}}"
  cust_lname:   "{{cust_lname}}"
  ship_city:    Houston
  ship_state:   Hexas

part03_email_info:
  cust_email:     "{{cust_email}}"
  mail_subject:   Thanks for your DoughNutz order!
  mail_notes: |
    We want the mail_greeting to have all the expected values
    with filled-in placeholders (and not curly-braces).
  mail_greeting: |
    Greetings {{cust_fname}} {{cust_lname}}!

    We love your motto "{{cust_motto}}" and we agree with you!

    Your total purchase price is {{prch_total_cost}}

    Thank you for your order!
Run Code Online (Sandbox Code Playgroud)

说明

  • 绿色标记的替换在标准YAML中很容易获得,使用锚点,别名和合并键.

  • 黄色标记的替换在技术上可用于标准YAML,但不是没有自定义类型声明或其他一些绑定机制.

  • 标记为YAML的RED中标记的替换不可用.然而,有一些解决方法和替代方案; 例如通过字符串格式化或字符串模板引擎(如python的yaml.load).

图像解释了YAML中不同类型的变量替换

细节

YAML经常请求的功能是能够插入任意变量占位符,这些占位符支持与同一(或转换)YAML文件中的其他内容相关的任意交叉引用和表达式.

YAML支持锚点和别名,但此功能不支持在YAML文本中的任何位置任意放置占位符和表达式.它们仅适用于YAML节点.

YAML还支持自定义类型声明,但这些不太常见,如果您接受来自可能不受信任的来源的YAML内容,则会产生安全隐患.

YAML插件库

有YAML扩展库,但这些不是本机YAML规范的一部分.

解决方法

  • 将YAML与模板系统结合使用,例如Jinja2或Twig
  • 使用YAML扩展库
  • 使用托管语言str.formatsprintf样式功能

也可以看看

  • 很好的答案,非常详细和解释,谢谢!不幸的是,标为绿色的部分不适用于 Jekyll 用户,至少在 Jekyll v3.8.5 上是这样。我测试了自己。 (2认同)
  • Jekyll 上有效的是 `&amp;hello` (别名)和 `*hello` (锚点),如下所述:https://idratherbewriting.com/documentation-theme-jekyll/mydoc_yaml_tutorial#example-6-variables (2认同)

lbo*_*vet 6

使用Yglu结构模板,您的示例可以写成:

foo: !()
  !? $.propname: 
     type: number 
     default: !? $.default

bar:
  !apply .foo: 
    propname: "some_prop"
    default: "some default"
Run Code Online (Sandbox Code Playgroud)

免责声明:我是作者或 Yglu。


归档时间:

查看次数:

55771 次

最近记录:

5 年,11 月 前