Start Coding

YAML Multi-line Strings

YAML multi-line strings are a powerful feature that allows you to include long text content in your YAML files. They're essential for maintaining readability and structure when dealing with complex data.

Types of Multi-line Strings

YAML offers two main types of multi-line strings:

1. Folded Style (>)

The folded style uses the '>' character and treats newlines as spaces, folding them into a single line.

description: >
  This is a long description
  that spans multiple lines.
  It will be folded into a single line.

This will be interpreted as: "This is a long description that spans multiple lines. It will be folded into a single line."

2. Literal Style (|)

The literal style uses the '|' character and preserves newlines, maintaining the exact formatting.

poem: |
  Roses are red,
  Violets are blue,
  YAML is awesome,
  And so are you!

This preserves the line breaks, keeping the poem's structure intact.

Indentation and Chomping

Proper indentation is crucial when working with multi-line strings in YAML. The content must be indented more than the key.

YAML also provides chomping indicators to control trailing newlines:

  • Strip chomping (-): Removes all trailing newlines
  • Keep chomping (+): Keeps all trailing newlines
  • Clip chomping (default): Keeps one trailing newline
stripped: |-
  This text will have
  no trailing newline.

kept: |+
  This text will keep
  all trailing newlines.


clipped: |
  This text will have
  one trailing newline.

Best Practices

  • Use folded style (>) for long prose that doesn't require specific formatting.
  • Use literal style (|) when preserving line breaks and formatting is important.
  • Be consistent with indentation to avoid parsing errors.
  • Consider using YAML Anchors for reusable multi-line strings.

Related Concepts

To further enhance your YAML skills, explore these related topics:

Understanding multi-line strings is crucial for working with complex YAML structures, especially when dealing with YAML for Application Configuration or YAML in Ansible.