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.
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.
YAML offers different stripping behaviors for literal scalars:
# 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 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.
Literal scalars are particularly useful in several scenarios:
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.