YAML – 块式样式
YAML - 块标量样式
Section titled “YAML - 块标量样式”YAML 提供了强大的块标量样式来表示多行字符串。这些样式可以对换行符和缩进的处理方式进行精细控制,使得 YAML 非常适合嵌入文本,例如脚本、诗歌或长描述。
两种主要的块标量样式是:
- Literal Style (
|): 保留块内的所有换行符。 - Folded Style (
>): 将换行符折叠为空格,但保留段落分隔(空行或缩进更多的行)。
这些样式由一个头部字符(| 或 >)发起,后面可以跟着“chomping indicators”(用于控制末尾换行符)以及可选的缩进指示符(不太常用)。
Literal Style (|)
Section titled “Literal Style (|)”字面量样式保留块内的所有换行符。YAML 源文件中的每个换行符在生成的字符串中都成为一个换行字符。每行开头的空白字符也会被保留。
literal_example: | This is the first line. This is the second line. This line is indented.
This line is after a blank line.literal_example 字符串将是(使用 \n 表示换行字符):
"This is the first line.\nThis is the second line.\n This line is indented.\n\nThis line is after a blank line.\n"Folded Style (>)
Section titled “Folded Style (>)”折叠样式专为长文本块设计。它将一个段落内的换行符折叠为空格。通过空行或缩进多于当前段落的行,会开始一个新的段落(在字符串中产生一个换行符)。
folded_example: > This is a long sentence that has been written on multiple lines in the YAML source.
This starts a new paragraph because of the blank line. This line starts another new paragraph because it's more indented.folded_example 字符串将是:
"This is a long sentence that has been written on multiple lines in the YAML source.\n\nThis starts a new paragraph because of the blank line.\n This line starts another new paragraph\n because it's more indented.\n"控制末尾换行符:Chomping Indicators
Section titled “控制末尾换行符:Chomping Indicators”Chomping indicators 控制块标量末尾的最终换行符如何处理。它们附加在样式指示符后面(例如,|-,>+)。共有三种类型:
Strip (-)
Section titled “Strip (-)”strip chomping indicator (-) 会移除块末尾的所有末尾换行符。如果块以一个或多个换行符结尾,它们全部会被移除。如果它不以换行符结尾,则不会发生任何变化。
strip_chomping: |- Line 1 Line 2
# (假设块在这里结束,在空行之后)strip_chomping 的结果字符串:"Line 1\nLine 2"(没有末尾换行符)。
Clip (默认)
Section titled “Clip (默认)”Clipping 是未指定 chomping indicator(或单独使用 | 或 >)时的默认行为。如果标量以一个或多个换行符结尾,clipping 会产生一个单独的末尾换行符。如果标量不以任何换行字符结尾(即,内容的最后一个字符不是换行符),则不会添加换行符。
clip_chomping_default: | Line 1 Line 2
# (块在空行后结束)
clip_chomping_no_final_char_newline: | Line 1 Line 2 # (假设此行中的 '2' 后面没有换行字符)clip_chomping_default 的结果字符串:"Line 1\nLine 2\n"(一个末尾换行符)。
clip_chomping_no_final_char_newline 的结果字符串(如果最后一个内容字符不是换行符):"Line 1\nLine 2"。
Keep (+)
Section titled “Keep (+)”keep chomping indicator (+) 保留所有末尾换行符。如果块标量以一个或多个换行符结尾,它们全部会在结果字符串中被保留。
keep_chomping: |+ Line 1 Line 2
# (块在两个空行后结束)keep_chomping 的结果字符串:"Line 1\nLine 2\n\n\n"(所有三个末尾换行符都被保留)。
块样式在各种场景下都非常有用:
- 在 YAML 中嵌入代码片段(例如,shell 脚本、JSON、SQL):此处通常首选字面量样式 (
|) 以保留精确格式。 - 存储多行文本,例如诗歌、提交消息或详细描述。
- 本身跨越多行的配置值,例如 SSH 密钥、SSL 证书或多行日志格式。
- 折叠样式 (
>) 对于长篇人类可读文本非常出色,它在 YAML 源文件中保持可读性的同时,将其折叠成一个带有适当段落分隔的连续字符串。
常见陷阱与最佳实践
Section titled “常见陷阱与最佳实践”- 缩进是关键:块标量的内容必须比其父键的缩进更多。块内部的不一致缩进(相对于其第一行)是内容的一部分。
- Chomping 的选择:理解 chomping indicators 的作用。不正确的 chomping 会导致意外的换行符或缺少换行符,这对于脚本或格式化文本可能至关重要。
- 折叠样式的细微差别:记住折叠样式 (
>) 只会在输出中为空行或源文件中缩进更多的行引入实际的换行符。其他换行符通常会被折叠为空格。 - 可读性:使用块样式可以增强 YAML 的可读性,特别是对于复杂的字符串值。
为了试验块样式、chomping 并实时查看它们的效果,可以考虑使用在线的 YAML 解析器或验证器。搜索“在线 YAML linter”或“在线 YAML parser”将提供一些有用的工具。