title | date | tags | |
---|---|---|---|
DRY YAML, Using Anchor and Alias |
2019-06-27 19:00:00 +0900 |
|
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.