英文:
Range over string or string array in Go template
问题
我正在编写一个使用连续字母字符的Go模板。以下是一个简单的示例:
{{ range $i, $e := until 2 }}
{{ range $a := .[]string{"a", "b", "c"} }}
<p>{{ $e }}{{ $a }}. Sample Text</p>
{{ end }}
<br>
{{ end }}
应该输出:
<p>0a. Sample Text</p>
<p>0b. Sample Text</p>
<p>0c. Sample Text</p>
<br>
<p>1a. Sample Text</p>
<p>1b. Sample Text</p>
<p>1c. Sample Text</p>
<br>
如果Go模板允许在模板内部以这种方式定义数组,上述代码将起作用。我需要类似于这个答案中的内容,但我不能编写自己的函数。我正在使用另一款软件来编写Go模板,但不能修改Go代码本身,也就是说不能传递变量。
我是否在要求不可能的事情?
英文:
I am writing a Go template that uses consecutive alpha characters. As a simple example:
{{ range $i, $e := until 2 }}
{{ range $a := .[]string{"a", "b", "c"} }}
<p>{{ $e }}{{ $a }}. Sample Text</p>
{{ end }}
<br>
{{ end }}
Should yield:
<p>0a. Sample Text</p>
<p>0b. Sample Text</p>
<p>0c. Sample Text</p>
<br>
<p>1a. Sample Text</p>
<p>1b. Sample Text</p>
<p>1c. Sample Text</p>
<br>
The above code would work if go templates let you define arrays this way inside the template. I would need something similar to this, or the answer here, with the exception that I am not able to write my own functions. I am using this for another piece of software that lets me write go templates, but I cannot modify the go code itself, meaning no passing variables either.
Am I asking the impossible?
答案1
得分: 1
看起来模板主机使用了Sprig。使用Sprig的list函数。
{{ range $i, $e := until 2 }}
{{ range $a := list "a" "b" "c" }}
<p>{{ $e }}{{ $a }}. 示例文本</p>
{{- end}}
<br>
{{- end}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论