Golang – HTML模板 – 范围限制

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

Golang - HTML Templating - Range limit

问题

我正在使用Go语言将一个切片打印到HTML文件中:

<ul>
{{range .arr}}
    <li>{{.}}</li>
{{end}}
</ul>

如果 len(arr) > 5,我该如何只打印切片的前5个元素?

英文:

I have a slice which I am printing to an html file in go:

&lt;ul&gt;
{{range .arr}}
    &lt;li&gt;{{.}}&lt;/li&gt;
{{end}}
&lt;/ul&gt;

If len(arr) &gt; 5, how do I print only the first 5 elements of the slice?

答案1

得分: 14

首先,我应该提到,如果你将一个数组传递给模板,那么你几乎肯定在做一些奇怪的事情。在Go中,数组相对较少使用。通常,你会使用切片

最简单的方法是在运行模板时传递数组的前5个元素的切片。

如果出于某种原因你需要在模板中使用完整的输入,你可以定义一个函数来获取切片,类似这样:

func mkslice(a []string, start, end int) []string {
    return a[start:end]
}

(参见如何将函数附加到模板的文档

然后在模板中使用:

{{range mkslice .arr 0 5}}
<li>{{.}}</li>
{{end}}

你也可以使用带有索引的range操作。

{{range $i, $val := .arr}}
{{if lt $i 5}}<li>{{$val}}</li>{{end}}
{{end}}
英文:

First off, I should mention that if you're passing an array to the template, you're almost certainly doing something weird. Arrays are relatively rarely used in Go. Typically, you would use a slice.

The easiest way would be to pass a slice of the first 5 elements of the array when running the template.

If you need the full input in the template for some reason, you could define a function for taking slices, something like this:

func mkslice(a []string, start, end int) []string {
    return a[start:end]
}

(see documentation for how to attach functions to templates)

And the template:

{{range mkslice .arr 0 5}}
&lt;li&gt;{{.}}&lt;/li&gt;
{{end}}

You could also use a form of the range action with an index.

{{range $i, $val := .arr}}
{{if lt $i 5}}&lt;li&gt;{{$val}}&lt;/li&gt;{{end}}
{{end}}

huangapple
  • 本文由 发表于 2015年5月6日 07:57:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/30065203.html
匿名

发表评论

匿名网友

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

确定