Start Coding

YAML Folded Scalars

YAML folded scalars are a powerful feature for handling multi-line strings in YAML documents. They provide a way to represent long text while maintaining readability and controlling line breaks.

What are Folded Scalars?

Folded scalars in YAML allow you to write multi-line strings that are treated as a single line when parsed. They use the > indicator followed by an optional chomping indicator.

Syntax and Usage

To create a folded scalar, use the following syntax:

key: >
  This is a folded scalar.
  Line breaks are converted to spaces,
  creating a single long line when parsed.

The > symbol indicates the start of a folded scalar. Subsequent indented lines are part of the scalar content.

Chomping Indicators

YAML provides chomping indicators to control trailing line breaks:

  • > (default): Keeps a single trailing newline
  • >-: Strips all trailing newlines
  • >+: Keeps all trailing newlines

Example: Using Folded Scalars

description: >
  This is a long description
  that spans multiple lines.
  It will be folded into a single line
  when parsed by a YAML processor.

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

multiline_with_breaks: >+
  This text will keep
  all of its line breaks,

  including the trailing ones.

When to Use Folded Scalars

Folded scalars are particularly useful in the following scenarios:

  • Long text content that doesn't require preserving line breaks
  • Improving readability of configuration files
  • Representing paragraphs or prose in data structures

Best Practices

  • Use folded scalars for human-readable text that doesn't rely on exact line breaks
  • Be mindful of indentation to ensure proper parsing
  • Consider using YAML Literal Scalars if preserving line breaks is crucial
  • Combine with YAML Comments for better documentation

Related Concepts

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

Understanding folded scalars is crucial for efficient data representation in YAML. They offer a balance between readability and compact storage, making them invaluable in various YAML Use Cases.