在yaml中使用占位符

问题描述 投票:18回答:1

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

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

bar:
    - *FOO 
       propname: "some_prop"
       default: "some default" 
yaml template-variables
1个回答
56
投票

上下文

  • 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:   [email protected]

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!

说明

  • 以绿色标记的取代在标准YAML中很容易获得,使用锚,别名和merge keys
  • 黄色标记的替代品在技术上可用于标准YAML,但不是没有custom type declaration或其他一些结合机制。
  • 标记为YAML的RED中标记的替换不可用。然而,有一些解决方法和替代方案;例如通过string formatting或字符串模板引擎(例如python的str.format)。

Image explaining the different types of variable substitution in YAML

细节

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

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

YAML还支持custom type declarations,但这些不太常见,如果您接受来自潜在不受信任来源的YAML内容,则存在安全隐患。

YAML addon libraries

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

解决方法

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

也可以看看

© www.soinside.com 2019 - 2024. All rights reserved.