Difference Between YAML Templates and Anchors

Both templates and anchors are used to create reusable structures, but they serve different purposes.

Anchors are used to mark a part of the document with a unique name that can be referenced later. Anchors are created using the “&” character followed by a name, and are followed by the data that you want to anchor. Here is an example of how to use an anchor:

# Define a dictionary with an anchor
person: &john
  name: John
  age: 30

# Use the anchor in another dictionary
other_person:
  <<: *john
  city: New York

In this example, the “&john” anchor is used to mark the “person” dictionary with the name “john”. The “other_person” dictionary uses the “<<: *john” syntax to merge the contents of the “john” dictionary into the “other_person” dictionary. This means that the “other_person” dictionary will contain the “name” and “age” keys from the “john” dictionary, as well as a new “city” key.

Templates, on the other hand, are used to create reusable structures that can be used multiple times within a document. Templates are created using anchors, but are followed by an alias that can be used to refer to the template later. Here is an example of how to use a template:

# Define a template for a person
&person_template
  name: John
  age: 30

# Use the person template in two places
first:
  person: *person_template
  city: New York

second:
  person: *person_template
  city: San Francisco

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 “city” key.

Follow us on social media
Follow Author