YAML Multiline Strings

Authors

In YAML, a multiline string is a way to represent a string that spans multiple lines.

Multiline strings are particularly useful for writing long blocks of text such as code snippets, configuration files, or even prose.

There are two types of multiline strings in YAML: folded and literal.

In a folded multiline string, line breaks are preserved, but any leading or trailing white space is removed.

In a literal multiline string, line breaks and white space are preserved exactly as they appear in the string.

Here's how to create each type of multiline string in YAML:

Folded Multiline Strings In YAML

To create a folded multiline string in YAML, use the greater than sign > followed by a newline character (indicated by the \n escape sequence) to start a new line.

Any leading or trailing white space will be removed, but line breaks will be preserved.

For example:

my_multiline_string: >
  This is a folded multiline string.
  It contains two lines of text.

In the example above, the folded multiline string has two lines of text.

The greater than sign indicates that the string is folded, and the newline character \n starts a new line.

Literal Multiline Strings In YAML

To create a literal multiline string in YAML, use the pipe character | followed by a newline character to start a new line.

Unlike folded multiline strings, a literal multiline string preserves all leading and trailing white space, as well as any line breaks.

For example:


my_multiline_string: |
  This is a literal multiline string.
  It contains two lines of text.

  The second line has an extra blank line above it.
  
    And this line has some leading white space.

In the example above, the literal multiline string has four lines of text, including an extra blank line between the second and third lines.

The pipe character indicates that the string is literal, and the newline character starts a new line.

Escaping Special Characters In YAML

If your multiline string contains special characters that need to be escaped (such as a colon), you can use double quotes to wrap the string.

This allows you to include special characters without needing to use escape sequences.

For example:

my_multiline_string: >
  "This string contains a colon: :"

In the example above, the double quotes allow you to include a colon without using an escape sequence.

That's it! With this guide, you should be able to create and work with multiline strings in YAML.

TrackingJoy