Repeating Nodes With YAML Aliases Like A Pro by@jasonheecs

Repeating Nodes With YAML Aliases Like A Pro

Read on Terminal Reader
Open TLDR
react to story with heart
react to story with light
react to story with boat
react to story with money
YAML allows you to repeat nodes via aliases. Aliases allow you to assign a name to a value or block of data. You can even modify a section of an alias and define that as a new alias. Alias should work for any file written in YAMl. The specification for the aliases is described in the YAM lspec.yAML specification here. You can use the merge key (>>:):YAML. The merge key is used to merge an alias into an alias.
image
Jason Hee HackerNoon profile picture

Jason Hee

A software engineer that loves tech

github social iconlinkedin social icon

Have you ever had to copy and paste duplicate content in a YAML file and wondered if it is possible to DRY that up? As it turns out, YAML allows you to repeat nodes via aliases.

YAML Aliases allow you to assign a name to a value or block of data and recall the assigned data by its name in the YAML file. Aliases should work for any file written in YAML.

Simple Example

hello: &hello 'hello'
greeting:
  audience: 'world'
  hello: *hello  #greeting.hello has the string value of 'hello'
new_greeting:
  audience: 'room'
  hello: *hello  #new_greeting.hello has the string value of 'hello'

Aliasing blocks of data

Besides string or number values, you can alias a block of data as well:

foo:
  bar: &bar
    qux: 'quxqux'
    baz: 'bazbaz'
greeting:
  audience: 'world'
  bar: *bar  #greeting.bar has the same values as foo.bar.
             #So greeting.bar.baz is 'bazbaz'

Modifying a section of an alias

You can copy an alias and modify a section of it by using the merge key (<<:):

bar: &bar
  qux: 'quxqux'
  baz: 'bazbaz'
greeting:
  audience: 'world'
  bar:
    <<: *bar       # greeting.bar.qux is 'quxqux'
    baz: 'notbaz'  # greeting.bar.baz is 'notbaz'

Defining aliases from modified aliases

You can even modify a section of an alias and define that as a new alias:

bar: &bar
  qux: 'quxqux'
  baz: 'bazbaz'
greeting:
  audience: 'world'
  bar: &newalias
    <<: *bar
    baz: 'notbaz'
new_greeting:
  audience: 'room'
  bar: *newalias  #new_greeting.bar.baz is 'notbaz'

YAML specification

Alias nodes are described in the YAML specification here.

Previously published at https://blog.jasonhee.com/how-to-use-yaml-aliases

react to story with heart
react to story with light
react to story with boat
react to story with money
L O A D I N G
. . . comments & more!