Start Coding

YAML Literal Scalars

YAML literal scalars are a powerful feature for handling multi-line strings in YAML files. They allow you to preserve newlines and indentation, making them ideal for representing code snippets, log entries, or any text where formatting is crucial.

Syntax and Usage

To create a literal scalar in YAML, use the pipe character (|) followed by the content on subsequent lines. The text will be treated exactly as written, preserving all newlines and spaces.

example: |
  This is a literal scalar.
  It preserves newlines and spaces.
    Indentation is also maintained.
  Empty lines are kept as well.

  Like this one above.

Stripping Behavior

YAML offers different stripping behaviors for literal scalars:

  • Clip (|): Keeps all content, including trailing newlines.
  • Strip (|-): Removes all trailing newlines.
  • Keep (|+): Preserves all trailing newlines.

Examples of Stripping Behavior

# Clip (default)
clip_example: |
  This text has one trailing newline.

# Strip
strip_example: |-
  This text has no trailing newlines.

# Keep
keep_example: |+
  This text keeps all trailing newlines.


Indentation in Literal Scalars

Indentation is significant in literal scalars. The first non-empty line sets the base indentation level, and subsequent lines are adjusted relative to this base.

example:
  |
    First line determines the base indentation.
      This line is indented two spaces from the base.
    Back to base indentation.
        Four spaces from base indentation.

Use Cases

Literal scalars are particularly useful in several scenarios:

  • Preserving formatting in code snippets
  • Maintaining structure in log entries
  • Representing configuration files or templates
  • Storing multi-line text data with precise formatting

Considerations and Best Practices

  • Use literal scalars when preserving exact formatting is crucial.
  • Be mindful of trailing spaces, as they are preserved in literal scalars.
  • For long text blocks, consider using YAML Folded Scalars if newline preservation isn't necessary.
  • When working with literal scalars, ensure your YAML parser correctly handles the chosen stripping behavior.

Understanding literal scalars is essential for effectively working with YAML Multi-line Strings and creating well-structured YAML documents. They provide a clean way to represent complex text data while maintaining readability and precision.