V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
suueyoung

golang 处理 yaml 时, 如何转义单引号, 双引号?

  •  
  •   suueyoung · Oct 12, 2020 · 3357 views
    This topic created in 2026 days ago, the information mentioned may be changed or developed.
    #sample.yml
    single: |
        a single quote'
    double: |
        a double quote"
    
    // main.go
    package main
    
    import (
    	"html/template"
    	"io/ioutil"
    	"log"
    	"os"
    
    	"gopkg.in/yaml.v2"
    )
    
    const Template = `{{ .Single}}
    ---
    {{ .Double}}`
    
    type Sample struct {
    	Single string `yaml:"single"`
    	Double string `yaml:"double"`
    }
    
    func main() {
    	file, err := ioutil.ReadFile("sample.yml")
    	if err != nil {
    		log.Fatal(err)
    	}
    	s := new(Sample)
    	err = yaml.Unmarshal(file, s)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	t, err := template.New("s").Parse(Template)
    	if err != nil {
    		log.Fatal(err)
    	}
    	err = t.Execute(os.Stdout, s)
    	if err != nil {
    		log.Fatal()
    	}
    }
    

    打印出来的是 ' 这样的字符.

    如果想要保留原始的 ' " , 要如何做呀?

    $ go run ./main.go
    a single quote'
    
    ---
    a double quote"
    
    4 replies    2020-10-12 13:59:03 +08:00
    vZexc0m
        1
    vZexc0m  
       Oct 12, 2020
    heimeil
        2
    heimeil  
       Oct 12, 2020   ❤️ 2
    type Sample struct {
    Single template.HTML `yaml:"single"`
    Double template.HTML `yaml:"double"`
    }
    suueyoung
        3
    suueyoung  
    OP
       Oct 12, 2020
    @heimeil 感谢~
    zunceng
        4
    zunceng  
       Oct 12, 2020   ❤️ 1
    你这代码 和 yaml 没半毛钱关系 是 template 干的

    import “html/template” => import “text/template”
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4283 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 04:06 · PVG 12:06 · LAX 21:06 · JFK 00:06
    ♥ Do have faith in what you're doing.