怎样在 YAML 源文件里分行写字符串,又不在值里加换行符?

June 16, 2025

假设应用从 YAML 配置文件里读取一条通知。你想在编辑器里分行写,发出去时仍然只有一行。Stack Overflow 上有个关于长字符串如何断行的问题,说的就是这件事。1 在配置项名称后写 >-,把消息缩进写在下面。行首的空格告诉 YAML 解析器哪些行属于 message。2

message: >-
  Your order is ready for pickup.
  Bring your receipt.

应用收到的是 Your order is ready for pickup. Bring your receipt.。> 选择折叠样式,两行缩进相同,中间的换行会变成一个空格。- 去掉句点后最后一个换行。消息可以直接输入,希望读者看到的引号也照写。3

如果想让带收据的提醒另起一行呢?只需把第一行改为 message: |-。竖线选择字面样式,会保留消息内部的换行。假设在最后一个句点后按了回车,同一段文字有以下四种结果。每个 \n 都代表一个换行符。3

YAML 写法应用收到的字符串
message: >-Your order is ready for pickup. Bring your receipt.
message: >Your order is ready for pickup. Bring your receipt.\n
message: |-Your order is ready for pickup.\nBring your receipt.
message: |Your order is ready for pickup.\nBring your receipt.\n

用 >- 时,要注意在哪里断行。把 pickup 拆成两行会得到 pick up。如果两个句子之间留一行空行,YAML 会在那里保留一个换行。要让一句话连续显示,就在词与词之间的空格处断行,并保持各行缩进一致。3

Footnotes

  1. jjkparker. (2010, September 24). How do I break a string in YAML over multiple lines? Stack Overflow. Question and examples. ↩

  2. 菜鸟教程. (n.d.). YAML 入门教程. Runoob. Basic syntax and indentation (in Chinese). ↩

  3. YAML Language Development Team. (2021, October 1). YAML Ain’t Markup Language (YAML™), revision 1.2.2. YAML.org. §8.1, Block Scalar Styles. ↩ ↩2 ↩3

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-06-16). 怎样在 YAML 源文件里分行写字符串,又不在值里加换行符?. https://caiborui.com/blog/2025-06-16-en-yaml-multiline-strings-zhtrans

@misc{borui2025-38e82a08,
  author = {borui},
  title = {{怎样在 YAML 源文件里分行写字符串,又不在值里加换行符?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-06-16-en-yaml-multiline-strings-zhtrans}
}