In YAML, breaking a string over multiple lines can be achieved using block styles or quoted strings, depending on whether you want to preserve newlines, whitespace, or formatting. Below are the most common methods with examples:
1. Block Scalar Styles (Preserve/Control Newlines)
Use |
(literal) or >
(folded) to handle multi-line strings. Indentation is critical here.
a. Literal Block (|
)
Preserves all newlines and indentation exactly as written.
Example:
literal_string: |
This is a
multi-line string
with preserved newlines.
Result:"This is a\nmulti-line string\nwith preserved newlines.\n"
b. Folded Block (>
)
Folds newlines into spaces (unless a line is empty or indented more).
Example:
folded_string: >
This is a folded string
that joins lines with spaces.
Empty lines start new paragraphs.
Result:"This is a folded string that joins lines with spaces.\nEmpty lines start new paragraphs.\n"
2. Chomping Modifiers (Control Trailing Newlines)
Add -
, +
, or nothing after |
or >
to control trailing newlines:
Modifier | Behavior |
---|---|
| /> | Keep trailing newline (default). |
|- />− | Strip trailing newline. |
|+ />+ | Keep all trailing newlines (including empty). |
Example:
no_trailing_newline: |-
This string
has no final newline.
3. Quoted Strings (Use \n
for Newlines)
Use "
or '
with explicit \n
for line breaks.
Example:
quoted_string: "Line 1\nLine 2\nLine 3"
Result:"Line 1\nLine 2\nLine 3"
4. Plain Scalars (Implicit Line Breaks)
For simple strings, break lines by indenting the next line:
plain_string: This is a plain
string split over
multiple lines.
Result:"This is a plain string split over multiple lines."
(Spaces replace line breaks.)
Key Rules
- Indentation: Lines must be indented more than the parent key.
- Empty Lines: In folded blocks (
>
), empty lines start new paragraphs. - Trailing Spaces: Use
\
at the end of a line to preserve a trailing space.
Examples by Use Case
Case 1: Preserve Formatting (Code Snippet)
code_snippet: |
function hello() {
console.log("Hello World");
}
Case 2: Long Paragraph (Folded)
description: >
This is a long description that wraps
into a single paragraph. Use folded
style for readability in YAML.
Case 3: Explicit Newlines (Quoted)
message: "Hello\nWorld\n"
Final Tips
- Use
|
for configuration files, scripts, or text requiring exact formatting. - Use
>
for prose or paragraphs where line breaks are not critical. - Avoid mixing styles unless necessary for readability.