Cool Yaml Features You Probably Didn’t Know About
https://faun.pub/cool-yaml-features-you-probably-didnt-know-cb15e8112576
Anchors
man:
name: Utibe
age: 1000
galaxy: milky-way
dinosaursExist: no
alien:
name: kal-el
age: 10000000
galaxy: milky-way
dinosaursExist: no
names:
- Utibe
- kal-el
As you can see, we have a names key that lists the
names
of bothman
andalien
. However, this is not ideal as we are writing out the names multiple times and if the name changes we have to change each reference to it. YAML has a feature known as anchors that allows us to reference a value. Here’s how it works
man:
name: &man Utibe
age: 1000
galaxy: milky-way
dinosaursExist: no
alien:
name: &alien kal-el
age: 10000000
galaxy: milky-way
dinosaursExist: no
names:
- *man
- *alien
Remove Redundancy With Anchors
metadata: &metadata
galaxy: milky-way
dinosaursExist: no
man:
name: &man Utibe
age: 1000
<<: *metadata
alien:
name: &alien kal-el
age: 10000000
<<: *metadata
names:
- *man
- *alien
And to overide standard template metadata in this example with specific values simply overwrite at the end as if the last thing read is what happens like in CSS
man:
name: &man Utibe
age: 1000
<<: *metadata
galaxy: another-galaxy
Explicit Tags
For data type casting
numbers:
num1: !!int 1.0 # converted to 1
num2: !!float 100 # converted to 100.0
num3: !!str 150 # converted to "150"
Multi-line strings
Literal Block
This preserves the \n
character at the end of each line, such as in a list of executed CLI commands
script: |
echo "hello world" > file.txt
cat file.txt
sed s/hello/Hello/g file.txt > file2.txt
mv file2.txt file.txt
Folded Block Approach
This treats the text as a single run on sentance with no new lines akin to:
script: Hello there This is some text but will be on the same line as the previous text
script: >
Hello there
This is some text
but will be on the same line as the previous text
Multiple YAML Docs in a single file
In YAML the compile sees ---
as a separator between 2 different YAML documents
name: "File one"
age: "one day"
planet: "earth"
---
name: "File two"
age: "two billion light years"
planet: "Jupiter"
Backlinks