如何将 YAML 中的字符串拆分为多行?

发布于 2024-09-25 07:06:41 字数 246 浏览 3 评论 0原文

我有一个很长的字符串:

Key: 'this is my very very very very very very long string'

我想通过多个较短的行来表达它,例如,

Key: 'this is my very very very ' +
     'long string'

我想使用上面的引号,这样我就不需要转义字符串中的任何内容。

I have a very long string:

Key: 'this is my very very very very very very long string'

I would like to express it over multiple shorter lines, e.g.,

Key: 'this is my very very very ' +
     'long string'

I would like to use quotes as above, so that I don't need to escape anything within the string.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

梦归所梦 2024-10-02 07:06:42

在 Jekyll 项目中的 YAML 文件中,上述解决方案都不适合我。在尝试了多种选项之后,我意识到使用
进行 HTML 注入也可以,因为最终所有内容都会呈现为 HTML:

name: |
在拉曼查的一个村庄
,我
不想记住它的名字。

至少它对我有用。不知道与此方法相关的问题。

None of the above solutions worked for me, in a YAML file within a Jekyll project. After trying many options, I realized that an HTML injection with <br> might do as well, since in the end everything is rendered to HTML:

name: |
In a village of La Mancha <br> whose name I don't <br> want to remember.

At least it works for me. No idea on the problems associated to this approach.

庆幸我还是我 2024-10-02 07:06:41

5 6 (或 63*,具体取决于您的计数方式)在 YAML 中编写多行字符串的不同方法。

TL;DR

  • 大多数情况下使用 >:内部换行符会被删除,尽管最后会得到一个换行符:

    <前><代码>键:>
    你的长
    字符串在这里。

  • 如果您希望保留这些换行符,请使用 |作为 \n (例如,带有段落的嵌入式降价)。

    <前><代码>键:|
    ### 标题

    * 项目符号
    * 积分

  • 如果您不想在末尾附加换行符,请使用 >-|-

  • 如果您需要在单词中间分割行或想要按字面意思将换行符键入为 \n,请使用 "..."

     键:“Antidisestab\
       lishmentarianism。\n\n继续吧。”
    
  • YAML 太疯狂了。

块标量样式(>|

这些允许诸如 \" 之类的字符无需转义,并添加在字符串末尾添加一个新行 (\n)

折叠样式删除字符串中的单个换行符(但在末尾添加一个换行符,并将双换行符转换为单行符):

Key: >
  this is my very very very
  long string

this是我非常非常长的字符串\n

保留额外的前导空格并导致额外的换行符。请参阅下面的

注释:通常这就是您想要的

文字样式
将字符串中的每个换行符转换为文字换行符,并在末尾添加一个换行符:

Key: |
  this is my very very very 
  long string

这是我非常非常\n长字符串\n

这是来自 YAML 规范 1.2

标量内容可以使用文字样式(用“|”表示)以块表示法编写,其中所有换行符都很重要。或者,可以使用折叠样式(用“>”表示)编写它们,其中每个换行符都会折叠到一个空格,除非它以空行或多缩进行结束。

建议:使用它来插入格式化文本(尤其是 Markdown)作为值。

带有块剪切指示符的块样式(>-|->+|+

)可以通过添加 块 chomping 指示符 字符:

  • >, |: "clip":保留换行,删除尾随空白行。
  • >-|-: "strip":去除换行符,去除尾随空白行。
  • >+|+: "keep":保留换行,保留尾随空白行。

“Flow”标量样式("'

这些样式具有有限的转义,并构造一个不带换行符的单行字符串。它们可以与键在同一行开始,或者首先添加额外的换行符,双倍换行符将成为一个换行符

。 /flow/plain" rel="noreferrer">普通样式(无转义,无 #: 组合,第一个字符不能是 "' 或许多其他标点符号):

Key: this is my very very very 
  long string

建议:避免。可能看起来很方便,但您可能会因为不小心使用禁止的标点符号并触发语法错误而搬起石头砸自己的脚。

双引号样式 (\" 必须通过 \ 转义,可以使用文字 \n 序列插入换行符,可以连接行没有空格,尾随 \):

Key: "this is my very very \"very\" loooo\
  ng string.\n\nLove, YAML."

“这是我非常非常“非常”的字符串。\n\n爱,YAML。

建议:在非常具体的情况下使用 唯一方法,并且可能在中间添加换行符是有用的。

这是在不添加空格的情况下跨行打破很长的标记(如 URL)的 org/spec/1.2/#style/flow/single-quoted" rel="noreferrer">单引号样式(文字 ' 必须双倍,无特殊字符,对于表达以双引号开头的字符串可能有用):

Key: 'this is my very very "very"
  long string, isn''t it.'

“这是我非常非常“非常”长的字符串,不是吗。”

建议:很少有好处,主要是不便。 如果

带有缩进指示符的块样式

以上内容对您来说还不够,您可以添加“块缩进指示器”(在块压缩指示器之后,如果有的话):

- >8
        My long string
        starts over here
- |+1
 This one
 starts here

注意:折叠样式中的前导空格 (>)

如果您在非开头插入额外的空格- 折叠样式的第一行将被保留,并带有额外的换行符。 (流样式不会发生这种情况。)第 6.5 节

此外,折叠不适用于包含前导空格的文本行周围的换行符。请注意,这样的缩进较多的行可能仅包含这样的前导空格。

- >
    my long
      string
                    
    many spaces above
- my long
      string
                    
    many spaces above
    

["my long\n string\n \n上面有很多空格\n","my long string\n上面有很多空格"]

摘要

在此表中: _ 表示 < code>空格字符,\n表示“换行符”,除非另有说明。 “前导空格”是指第二行上的附加空格字符,而第一行仅为空格(用于建立缩进)。

>|>-|->+| +"'
空格/换行符转换为:
尾随空格 →______
前导空格 →\n_\n_\n_\n_\n_\n_
单换行符 →_\n\_n _\n___
双换行符 →\n\n\n\n\n\n\n \n\n\n \n\n
最后换行 →\n\n\n\n
最后的双换行符 →\n\n\n\n\n\n
如何创建文字:
单引号''''''''其他
双引号"""""""\""
反斜杠\\\\\\\\ \\
功能
内嵌换行符 \n

There are 5 6 NINE (or 63*, depending how you count) different ways to write multi-line strings in YAML.

TL;DR

  • Use > most of the time: interior line breaks are stripped out, although you get one at the end:

      key: >
        Your long
        string here.
    
  • Use | if you want those linebreaks to be preserved as \n (for instance, embedded markdown with paragraphs).

      key: |
        ### Heading
    
        * Bullet
        * Points
    
  • Use >- or |- instead if you don't want a linebreak appended at the end.

  • Use "..." if you need to split lines in the middle of words or want to literally type linebreaks as \n:

      key: "Antidisestab\
       lishmentarianism.\n\nGet on it."
    
  • YAML is crazy.

Block scalar styles (>, |)

These allow characters such as \ and " without escaping, and add a new line (\n) to the end of your string.

> Folded style removes single newlines within the string (but adds one at the end, and converts double newlines to singles):

Key: >
  this is my very very very
  long string

this is my very very very long string\n

Extra leading space is retained and causes extra newlines. See note below.

Advice: Use this. Usually this is what you want.

| Literal style
turns every newline within the string into a literal newline, and adds one at the end:

Key: |
  this is my very very very 
  long string

this is my very very very\nlong string\n

Here's the official definition from the YAML Spec 1.2

Scalar content can be written in block notation, using a literal style (indicated by “|”) where all line breaks are significant. Alternatively, they can be written with the folded style (denoted by “>”) where each line break is folded to a space unless it ends an empty or a more-indented line.

Advice: Use this for inserting formatted text (especially Markdown) as a value.

Block styles with block chomping indicator (>-, |-, >+, |+)

You can control the handling of the final new line in the string, and any trailing blank lines (\n\n) by adding a block chomping indicator character:

  • >, |: "clip": keep the line feed, remove the trailing blank lines.
  • >-, |-: "strip": remove the line feed, remove the trailing blank lines.
  • >+, |+: "keep": keep the line feed, keep trailing blank lines.

"Flow" scalar styles (, ", ')

These have limited escaping, and construct a single-line string with no new line characters. They can begin on the same line as the key, or with additional newlines first, which are stripped. Doubled newline characters become one newline.

plain style (no escaping, no # or : combinations, first character can't be ", ' or many other punctuation characters ):

Key: this is my very very very 
  long string

Advice: Avoid. May look convenient, but you're liable to shoot yourself in the foot by accidentally using forbidden punctuation and triggering a syntax error.

double-quoted style (\ and " must be escaped by \, newlines can be inserted with a literal \n sequence, lines can be concatenated without spaces with trailing \):

Key: "this is my very very \"very\" loooo\
  ng string.\n\nLove, YAML."

"this is my very very \"very\" loooong string.\n\nLove, YAML."

Advice: Use in very specific situations. This is the only way you can break a very long token (like a URL) across lines without adding spaces. And maybe adding newlines mid-line is conceivably useful.

single-quoted style (literal ' must be doubled, no special characters, possibly useful for expressing strings starting with double quotes):

Key: 'this is my very very "very"
  long string, isn''t it.'

"this is my very very \"very\" long string, isn't it."

Advice: Avoid. Very few benefits, mostly inconvenience.

Block styles with indentation indicators

Just in case the above isn't enough for you, you can add a "block indentation indicator" (after your block chomping indicator, if you have one):

- >8
        My long string
        starts over here
- |+1
 This one
 starts here

Note: Leading spaces in Folded style (>)

If you insert extra spaces at the start of not-the-first lines in Folded style, they will be kept, with a bonus newline. (This doesn't happen with flow styles.) Section 6.5:

In addition, folding does not apply to line breaks surrounding text lines that contain leading white space. Note that such a more-indented line may consist only of such leading white space.

- >
    my long
      string
                    
    many spaces above
- my long
      string
                    
    many spaces above
    

["my long\n string\n \nmany spaces above\n","my long string\nmany spaces above"]

Summary

In this table: _ means space character, \n means "newline character" except were noted. "Leading space" refers to an additional space character on the second line, when the first is only spaces (which establishes the indent).

>|>-|->+|+"'
Spaces/newlines converted to:
Trailing space →______
Leading space →\n_\n_\n_\n_\n_\n_
Single newline →_\n_\n_\n___
Double newline →\n\n\n\n\n\n\n\n\n\n\n\n
Final newline →\n\n\n\n
Final double newline →\n\n\n\n\n\n
How to create a literal:
Single quote''''''''''
Double quote"""""""\""
Backslash\\\\\\\\\\
Other features
In-line newlines with literal \n????????????????????????????????
Spaceless newlines with \????????????????????????????????
# or : in value????
Can start on same
line as key
????????????????????????

Examples

Note the trailing spaces on the line before "spaces."

- >
  very "long"
  'string' with

  paragraph gap, \n and        
  spaces.
- | 
  very "long"
  'string' with

  paragraph gap, \n and        
  spaces.
- very "long"
  'string' with

  paragraph gap, \n and        
  spaces.
- "very \"long\"
  'string' with

  paragraph gap, \n and        
  s\
  p\
  a\
  c\
  e\
  s."
- 'very "long"
  ''string'' with

  paragraph gap, \n and        
  spaces.'
- >- 
  very "long"
  'string' with

  paragraph gap, \n and        
  spaces.

[
  "very \"long\" 'string' with\nparagraph gap, \\n and         spaces.\n", 
  "very \"long\"\n'string' with\n\nparagraph gap, \\n and        \nspaces.\n", 
  "very \"long\" 'string' with\nparagraph gap, \\n and spaces.", 
  "very \"long\" 'string' with\nparagraph gap, \n and spaces.", 
  "very \"long\" 'string' with\nparagraph gap, \\n and spaces.", 
  "very \"long\" 'string' with\nparagraph gap, \\n and         spaces."
]

*2 block styles, each with 2 possible block chomping indicators (or none), and with 9 possible indentation indicators (or none), 1 plain style and 2 quoted styles: 2 x (2 + 1) x (9 + 1) + 1 + 2 = 63

Some of this information has also been summarised here.

私野 2024-10-02 07:06:41

使用yaml折叠样式。每行中的缩进将被忽略。将在末尾插入换行符。

Key: >
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  with only a single carriage return appended to the end.

http://symfony.com/doc/current/components/yaml/yaml_format.html

您可以使用“块剪切指示器”来消除尾随换行符,如下所示:

Key: >-
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  with NO carriage returns.

在任何一种情况下,每个换行符都会替换为空格。

还有其他可用的控制工具(例如用于控制缩进)。

请参阅 https://yaml-multiline.info/

Using yaml folded style. The indention in each line will be ignored. A line break will be inserted at the end.

Key: >
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  with only a single carriage return appended to the end.

http://symfony.com/doc/current/components/yaml/yaml_format.html

You can use the "block chomping indicator" to eliminate the trailing line break, as follows:

Key: >-
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  with NO carriage returns.

In either case, each line break is replaced by a space.

There are other control tools available as well (for controlling indentation for example).

See https://yaml-multiline.info/

初与友歌 2024-10-02 07:06:41

要保留换行符,请使用|,例如:

Key: |
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  with newlines preserved.

翻译为“这是一个非常长的句子‌**\n**,跨越多行在 YAML‌**\n** 中,但它将呈现为字符串‌**\n** 并保留换行符。\n

To preserve newlines use |, for example:

Key: |
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  with newlines preserved.

is translated to "This is a very long sentence‌**\n** that spans several lines in the YAML‌**\n** but which will be rendered as a string‌**\n** with newlines preserved.\n"

鹤舞 2024-10-02 07:06:41

1.块表示法(普通、流式、标量): 删除块后换行符变为空格和多余的换行符

---
# Note: It has 1 new line after the string
content:
    Arbitrary free text
    over multiple lines stopping
    after indentation changes...

...

等效 JSON

{
 "content": "Arbitrary free text over multiple lines stopping after indentation changes..."
}

2.文字块标量: 文字块标量 | 将包含换行符和任何尾随空格。但删除

块后多余的换行符。

---
# After string we have 2 spaces and 2 new lines
content1: |
 Arbitrary free text
 over "multiple lines" stopping
 after indentation changes...  


...

等效 JSON

{
 "content1": "Arbitrary free text\nover \"multiple lines\" stopping\nafter indentation changes...  \n"
}

3. + 带有文字块标量的指示器: 在块后保留额外的换行符

---
# After string we have 2 new lines
plain: |+
 This unquoted scalar
 spans many lines.


...

等效 JSON

{
 "plain": "This unquoted scalar\nspans many lines.\n\n\n"
}

4. – 带文字块标量的指示器: 表示删除字符串末尾的换行符。

---
# After string we have 2 new lines
plain: |-
 This unquoted scalar
 spans many lines.


...

等效 JSON

{
 "plain": "This unquoted scalar\nspans many lines."
}

5.折叠块标量(>):

将换行符折叠为空格,但会删除块后多余的换行符。

---
folded_newlines: >
 this is really a
 single line of text
 despite appearances


...

等效 JSON

{
 "fold_newlines": "this is really a single line of text despite appearances\n"
}

有关更多信息,您可以访问我的博客

1. Block Notation(plain, flow-style, scalar): Newlines become spaces and extra newlines after the block are removed

---
# Note: It has 1 new line after the string
content:
    Arbitrary free text
    over multiple lines stopping
    after indentation changes...

...

Equivalent JSON

{
 "content": "Arbitrary free text over multiple lines stopping after indentation changes..."
}

2. Literal Block Scalar: A Literal Block Scalar | will include the newlines and any trailing spaces. but removes extra

newlines after the block.

---
# After string we have 2 spaces and 2 new lines
content1: |
 Arbitrary free text
 over "multiple lines" stopping
 after indentation changes...  


...

Equivalent JSON

{
 "content1": "Arbitrary free text\nover \"multiple lines\" stopping\nafter indentation changes...  \n"
}

3. + indicator with Literal Block Scalar: keep extra newlines after block

---
# After string we have 2 new lines
plain: |+
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines.\n\n\n"
}

4. – indicator with Literal Block Scalar: means that the newline at the end of the string is removed.

---
# After string we have 2 new lines
plain: |-
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines."
}

5. Folded Block Scalar(>):

will fold newlines to spaces and but removes extra newlines after the block.

---
folded_newlines: >
 this is really a
 single line of text
 despite appearances


...

Equivalent JSON

{
 "fold_newlines": "this is really a single line of text despite appearances\n"
}

for more you can visit my Blog

梦明 2024-10-02 07:06:41

要连接长行不带空格,请使用双引号并使用反斜杠转义换行符:

key: "Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemp\
  orincididuntutlaboreetdoloremagnaaliqua."

To concatenate long lines without whitespace, use double quotes and escape the newlines with backslashes:

key: "Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemp\
  orincididuntutlaboreetdoloremagnaaliqua."
寄与心 2024-10-02 07:06:41

你可能不相信,YAML 也可以做多行键:

?
 >
 multi
 line
 key
:
  value

You might not believe it, but YAML can do multi-line keys too:

?
 >
 multi
 line
 key
:
  value
七度光 2024-10-02 07:06:41

如果您在 Symfony 中使用 YAML 和 Twig 进行翻译,并且想要在 Javascript 中使用多行翻译,则会在翻译后立即添加回车符。因此,即使是以下代码:

var javascriptVariable = "{{- 'key'|trans -}}";

其中有以下 yml 翻译:

key: >
    This is a
    multi line 
    translation.

仍然会在 html 中生成以下代码:

var javascriptVariable = "This is a multi line translation.
";

因此, Twig 中的减号并不能解决这个问题。解决方案是在 yml 中的大于号后面添加这个减号:

key: >-
    This is a
    multi line 
    translation.

将得到正确的结果,在 Twig 中的一行上进行多行翻译:

var javascriptVariable = "This is a multi line translation.";

In case you're using YAML and Twig for translations in Symfony, and want to use multi-line translations in Javascript, a carriage return is added right after the translation. So even the following code:

var javascriptVariable = "{{- 'key'|trans -}}";

Which has the following yml translation:

key: >
    This is a
    multi line 
    translation.

Will still result into the following code in html:

var javascriptVariable = "This is a multi line translation.
";

So, the minus sign in Twig does not solve this. The solution is to add this minus sign after the greater than sign in yml:

key: >-
    This is a
    multi line 
    translation.

Will have the proper result, multi line translation on one line in Twig:

var javascriptVariable = "This is a multi line translation.";
空名 2024-10-02 07:06:41

对于字符串可能包含空格或不包含空格的情况,我更喜欢双引号和带反斜杠的续行:

key: "String \
  with long c\
  ontent"

但请注意续行以空格开头的情况的陷阱,需要对其进行转义(因为它将被剥离)其他地方):

key: "String\
  \ with lon\
  g content"

如果字符串包含换行符,则需要以 C 风格 \n 编写。

另请参阅此问题。

For situations were the string might contain spaces or not, I prefer double quotes and line continuation with backslashes:

key: "String \
  with long c\
  ontent"

But note about the pitfall for the case that a continuation line begins with a space, it needs to be escaped (because it will be stripped away elsewhere):

key: "String\
  \ with lon\
  g content"

If the string contains line breaks, this needs to be written in C style \n.

See also this question.

夜夜流光相皎洁 2024-10-02 07:06:41

如果上述解决方案都不适合您,请尝试在 HTML 元素上添加 white-space: pre-line ,并按如下所示设置翻译值:

key: "Line1\nLine2"

If none of the above solutions work with you, try adding white-space: pre-line on your HTML element, and setting your translation value like this :

key: "Line1\nLine2"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文