Back to: YAML Templates
Templates are used to define reusable structures for data that is used throughout a document. Templates are created using anchors and aliases, and can be included in other parts of the document using references. Here is an example of a YAML template:
# Define a template for a person
&person_template
name: John
age: 30
# Use the person template in two places
first:
person: *person_template
location:
city: New York
state: NY
second:
person: *person_template
location:
city: San Francisco
state: CA
In this example, the “&person_template” anchor defines a dictionary that contains the “name” and “age” keys. The “first” and “second” dictionaries both use the alias “*person_template” to reference the template, which means they will both contain the “name” and “age” keys. Each dictionary also has its own “location” dictionary.
Templates can also be used to define more complex data structures that include lists and dictionaries. Here is an example of a YAML template that includes a nested list:
# Define a template for a grocery list
&grocery_template
store: Safeway
items:
- name: Apple
quantity: 5
- name: Orange
quantity: 10
# Use the grocery template in two places
first:
groceries: *grocery_template
second:
groceries:
store: Whole Foods
items:
- name: Banana
quantity: 7
- name: Pineapple
quantity: 1
In this example, the “&grocery_template” anchor defines a dictionary that contains a “store” key and a “items” key that points to a list of dictionaries. The “first” and “second” dictionaries both use the alias “*grocery_template” to reference the template, which means they will both contain the “store” and “items” keys. The “second” dictionary also overrides the “store” key with a new value.
Follow us on social media
Follow Author