YAML – 块标头
YAML - 块标量(Block Scalars)(多行字符串)
Section titled “YAML - 块标量(Block Scalars)(多行字符串)”YAML 提供了强大的机制来表示多行字符串,称为块标量(block scalars)。它们对于嵌入文本块、代码片段或任何跨多行字符串数据特别有用。块标量主要有两种类型:字面量样式(literal style)和折叠样式(folded style)。
注释可以出现在块标量内容之前或之后,但不应穿插在标量的行中,因为它们会成为字符串内容的一部分。
字面量样式(Literal Style)(|)
Section titled “字面量样式(Literal Style)(|)”字面量样式由管道符(|)表示,它会保留块内的所有换行符(newline)。YAML 源代码中的每个换行都转换为结果字符串中的换行符。块标量内容的缩进(相对于起始的 | 行)会被去除。
poem: | Roses are red, Violets are blue, Sugar is sweet, And so are you.解析后 poem 的字符串值为:“Roses are red,\nViolets are blue,\nSugar is sweet,\nAnd so are you.\n” (注意,如果内容最后一行存在尾随换行符,它也会被保留;如果不存在且未使用切除修饰符(chomped),则默认会添加一个)。
折叠样式(Folded Style)(>)
Section titled “折叠样式(Folded Style)(>)”折叠样式由大于号(>)表示,通常会将块内的换行符转换为空格。但是,它会保留后面跟着更深缩进行或以空白行(段落分隔符)形式出现的换行符。
description: > This is a long description that spans multiple lines. It will be folded into a single line, with newlines replaced by spaces.
Paragraph breaks, however, like this one, are preserved as newlines.解析后 description 的字符串值为:“This is a long description that spans multiple lines. It will be folded into a single line, with newlines replaced by spaces.\nParagraph breaks, however, like this one, are preserved as newlines.\n”
切除修饰符(Chomping Modifiers)
Section titled “切除修饰符(Chomping Modifiers)”字面量样式和折叠样式都可以使用切除修饰符(chomping modifiers)来控制末尾换行符的处理方式:
- **
-(切除/strip):**移除所有尾随的换行符。例如,|-或>-。 - **
+(保留/keep):**保留所有尾随的换行符,包括块以多个空行结束时最末尾的换行符。例如,|+或>+。 - **默认(截断/clip):**如果没有指定修饰符(
|或>),则保留一个尾随换行符;额外的尾随空白行会被移除。
strip_example: |- Line 1 Line 2
# 结果: "Line 1\nLine 2"
keep_example: |+ Line A Line B
# 结果: "Line A\nLine B\n\n\n"
clip_example: | Line X Line Y
# 结果: "Line X\nLine Y\n"(假设 Line Y 后面有一个换行符)缩进(Indentation)
Section titled “缩进(Indentation)”块标量内容的缩进决定了每行要去除多少前导空白字符。解析器(parser)会检测内容行的最小缩进级别,并移除等量的先导空白。如果某行的缩进少于第一条内容行,则表示标量结束(除非它是空行,可能根据样式保留)。
块标量对于在 YAML 文档中清晰地嵌入大块文本至关重要,这使得文档高度可读且易于维护。