代码之家  ›  专栏  ›  技术社区  ›  xpt

Go templates:如何访问模板中的子字符串(s[:2])?

  •  0
  • xpt  · 技术社区  · 4 年前

    类似 Go templates: How do I access array item (arr[2]) in templates?
    如何直接访问Go模板中的子字符串(例如s[:2])?

    每当我这样做时,我都会得到“坏字符U+005B'[]”

    {{ .s[:2] }}
    
    0 回复  |  直到 4 年前
        1
  •  3
  •   icza    4 年前

    您可以使用 slice 上的模板函数 string s也是(添加在 Go 1.13 ):

    Template functions:

    slice
      slice returns the result of slicing its first argument by the
      remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2],
      while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3"
      is x[1:2:3]. The first argument must be a string, slice, or array.
    

    例如:

    t := template.Must(template.New("").Parse(`{{ slice . 0 2 }}`))
    if err := t.Execute(os.Stdout, "abcdef"); err != nil {
        panic(err)
    }
    

    这将输出(在上尝试 Go Playground ):

    ab
    

    不要忘记Go字符串存储UTF-8编码的字节序列,而索引和切片字符串使用字节索引(而不是 rune 索引)。当字符串包含多字节符文时,这很重要,如本例所示:

    t := template.Must(template.New("").Parse(`{{ slice . 0 3 }}`))
    if err := t.Execute(os.Stdout, "世界"); err != nil {
        panic(err)
    }
    

    这将输出一个 符文 (在上试试 Go Playground ):

    世