Hero Image
YAML 裡的字串很長該怎麼做?

YAML 裡的字串很長該怎麼做? 在 YAML 裡已經有規範此部份,在這種情況有四種方法可以幫助我們: |: 其下內容的換行,就是換行,最後一行會有換行。 >: 其下內容的換行,不會是換行,會變為一個很長的字串,最後會有換行。 |-: 其下內容的換行,就是換行,但最後一行不會有換行。 >-: 其下內容的換常,不會是換行,最後一行也不會有換行。 簡單的說,> 跟 >- 可以增加 YAML 的可讀性,又不會有多餘的換行符號。而 | 跟 |- 則可以讓字串跟定義的一致,在 YAML 裡看到換行,那字串裡就會有換行符號。 --- - name: Test long string hosts: all vars: s1: "hello" s2: | s2 this is my very very very long string line1 line2 line3 s3: > s3 this is my very very very long string line1 line2 line3 s4: |- s4 this is my very very very long string line1 line2 line3 s5: >- s5 this is my very very very long string line1 line2 line3 tasks: - name: s1 copy: content: "{{ s1 }}" dest: "/tmp/s1.txt" # hello% - name: s2 copy: content: "{{ s2 }}" dest: "/tmp/s2.txt" # s2 # this is my very very very # long string # line1 # line2 # line3 - name: s3 copy: content: "{{ s3 }}" dest: "/tmp/s3.txt" # s3 this is my very very very long string line1 line2 line3 - name: s4 copy: content: "{{ s4 }}" dest: "/tmp/s4.txt" # s4 # this is my very very very # long string # line1 # line2 # line3% - name: s5 copy: content: "{{ s5 }}" dest: "/tmp/s5.txt" # s5 this is my very very very long string line1 line2 line3%

Hero Image
多數程式設計師不知道的 6 個 YAML 特性

多數程式設計師不知道的 6 個 YAML 特性 還有更多類似的危險例子,正如 Tom Ritchford 所指出 013 會被對應為 11,因為前導 0 會觸發八進位表示法 4:30 會被對應為 270。Max Werner Kaul-Gothe 與 Niklas Baumstark 告訴我,這會被自動轉換為分鐘(或秒)並被視為一段持續時間:4*60 + 30 = 270。有趣的是,這個模式在 1:1:1:1:1:1:1:1:4:30 仍然「可運作」。 多行字串 mail_signature: | Martin Thoma Tel. +49 123 4567 { "mail_signature": "Martin Thoma\nTel. +49 123 4567" } 錨點 & 會定義一個名為 emailAddress 的變數,值為 "info@example.de"。* 則表示接著的是變數名稱。 email: &emailAddress "info@example.de" id: *emailAddress { "email": "info@example.de", "id": "info@example.de" } 也可以對映射這樣做 foo: &default_settings db: host: localhost name: main_db port: 1337 email: admin: admin@example.com prod: <<: *default_settings app: port: 80 dev: *default_settings { "foo": { "db": { "host": "localhost", "name": "main_db", "port": 1337 }, "email": { "admin": "admin@example.com" } }, "prod": { "app": { "port": 80 }, "db": { "host": "localhost", "name": "main_db", "port": 1337 }, "email": { "admin": "admin@example.com" } }, "dev": { "db": { "host": "localhost", "name": "main_db", "port": 1337 }, "email": { "admin": "admin@example.com" } } } 型別轉換 雙驚嘆號 !! 在 YAML 中有特殊意義。它稱為「secondary tag handle」,是 !tag:yaml.org,2002 的簡寫。