yamlplaceholdercomputed-propertiesindirectiontemplate-variables

Use placeholders in YAML


Is there a way to use placeholders in YAML like this:

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

bar:
    - *FOO 
       propname: "some_prop"
       default: "some default" 

Solution

  • Context

    Problem

    Example

    Consider the following example YAML. It is well-formed YAML syntax, however it uses (non-standard) curly-brace placeholders with embedded expressions.

    The embedded expressions do not produce the desired result in YAML, because they are not part of the native YAML specification. Nevertheless, they are used in this example only to help illustrate what is available with standard YAML and what is not.

    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}}
        
    

    Explanation

    Image explaining the different types of variable substitution in YAML

    Details

    Templates with variable placeholders is a frequently-requested YAML feature.

    Routinely, developers want to cross-reference content in the same YAML file or transcluded YAML file(s).

    YAML supports anchors and aliases, but this feature does not support arbitrary placement of placeholders and expressions anywhere in the YAML text. They only work with YAML nodes.

    YAML also supports custom type declarations, however these are less common, and there are security implications if you accept YAML content from potentially untrusted sources.

    YAML addon libraries

    There are YAML extension libraries, but these are not part of the native YAML spec.

    Workarounds

    Alternatives

    See also

    Here at SO

    Outside SO