How do I access substrings (s[:2]) in Go templates?

huangapple go评论64阅读模式
英文:

How do I access substrings (s[:2]) in Go templates?

问题

类似于https://stackoverflow.com/questions/31235211/
如何在Go模板中直接访问子字符串(例如s[:2])?

每当我这样做时,我得到"bad character U+005B '['"的错误提示。

{{ .s[:2] }}

英文:

Similar to https://stackoverflow.com/questions/31235211/
How do I directly access substrings (e.g. s[:2]) in Go templates?

Whenever I do this I get "bad character U+005B '['"

{{ .s[:2] }}

答案1

得分: 3

你也可以在字符串上使用slice模板函数(它在Go 1.13中添加):

模板函数:

slice
slice函数返回将第一个参数按照剩余参数进行切片的结果。因此,"slice x 1 2"在Go语法中表示x[1:2],而"slice x"表示x[:],"slice x 1"表示x[1:],"slice x 1 2 3"表示x[1:2:3]。第一个参数必须是字符串、切片或数组。

例如:

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)
}

这将输出一个单独的rune(在Go Playground上尝试):

英文:

You may use the slice template function on strings too (it was added in 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.

For example:

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

This will output (try it on the Go Playground):

ab

Don't forget that Go strings store the UTF-8 encoded byte sequence, and indexing and slicing strings uses the byte index (not the rune index). This matters when the string contains multi-byte runes, like in this example:

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

This will output a single rune (try it on the Go Playground):

huangapple
  • 本文由 发表于 2022年1月18日 04:38:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/70747251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定