Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kodaka/7a956444ba687d772c25e8f45cf2e394 to your computer and use it in GitHub Desktop.
Save kodaka/7a956444ba687d772c25e8f45cf2e394 to your computer and use it in GitHub Desktop.
title date tags
DRY YAML, Using Anchor and Alias
2019-06-27 19:00:00 +0900
yaml

Sometimes there are same keys or values in one YAML.

Not to repeat yourself, it is good to use anchor and alias features. It is useful when writing something like "config.yaml"-ish files.

If you have like this:

a: 1
b: 1
c:
  foo: bar
  buz: 1
d:
  foo: bar
  buz: 1

You can name (anchor) for repeated value 1 with & prefixed:

a: &nameyouwant 1
b: 1
c:
  foo: bar
  buz: 1
d:
  foo: bar
  buz: 1

And you can use (alias) it with * prefixed:

a: &nameyouwant 1
b: *nameyouwant
c:
  foo: bar
  buz: *nameyouwant
d:
  foo: bar
  buz: *nameyouwant

You can also anchor for:

a: &nameyouwant 1
b: *nameyouwant
c: &anothernameyouwant
  foo: bar
  buz: *nameyouwant
d:
  foo: bar
  buz: *nameyouwant

And alias:

a: &nameyouwant 1
b: *nameyouwant
c: &anothernameyouwant
  foo: bar
  buz: *nameyouwant
d: *anothernameyouwant

YAML has more complicated syntax about them, but I think it is easiser to read while using less just like above.

Online YAML Parser will help you to test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment