LE:我重新阅读了你的问题,并意识到我最初误解了你的目标。我已经重做了答案,希望这次我做对了。
为了在迭代项目时向项目添加CSS 类,即在同一页面上显示多个,我保留了下面的旧答案。
要在项目自己的页面上添加一个类,具体取决于它在全局列表中的位置,试试这个。
列表和排序
将$allPosts 中的项目汇总起来。默认情况下,我认为它们是按.Date 降序排列的,即最新的在前。要强制您自己的顺序或标准,您可以使用sort。
{{ $allPosts := where site.RegularPages "Type" "posts" }}
{{ $allPostsByDate := sort $allPosts ".Date" "asc" }}
感兴趣的页面
获取特别的物品。对于第一个和最后一个,您可以使用它们各自的内置函数; first 和 last 都返回具有一个元素(在本例中为页面)的数组,因此要提取一个元素,您可以使用 index。
{{ $firstPost := index (first 1 $allPostsByDate) 0 }}
{{ $lastPost := index (last 1 $allPostsByDate) 0 }}
与当前页面比较
此示例中的所有代码都必须包含在模板中,例如single.html,该模板针对每个页面运行。因此,对于呈现的每个页面,您都要做最后一次检查,以查看当前页面是否是特殊页面之一。
我不太了解 Hugo 是否有更好的方法来比较两个页面,但 .Permalinks 似乎足够好。
{{ if eq $firstPost.Permalink $.Permalink }} first-post {{ end }}
{{ if eq $lastPost.Permalink $.Permalink }} last-post {{ end }}
整件事
显示整个列表,用于可视化是什么。
{{ $allPosts := where site.RegularPages "Type" "posts" }}
{{ $allPostsByDate := sort $allPosts ".Date" "asc" }}
{{ $firstPost := index (first 1 $allPostsByDate) 0 }}
{{ $lastPost := index (last 1 $allPostsByDate) 0 }}
{{/* on the single page */}}
{{ .Title }} —
{{ if eq $firstPost.Permalink $.Permalink }} first-post {{ end }}
{{ if eq $lastPost.Permalink $.Permalink }} last-post {{ end }}
<br><br>
{{/* on a list */}}
{{ range $allPostsByDate }}
<a href="{{ .Permalink }}">{{ .Title }}</a>
{{ if eq $firstPost.Permalink .Permalink }} first-post {{ end }}
{{ if eq $lastPost.Permalink .Permalink }} last-post {{ end }}
<br>
{{ end }}
旧答案
最后使用 Hugo
我认为那里可能有错字?我现在无法测试,但我会说你需要一个点而不是问号。我不知道 $ 变量是什么,如果它在 Hugo 中。事实上,这可以解释错误。 last 期望第二个参数是一个数组,你给它一个 PageState。所以应该是这样的:
{{ $last_posts := last 1 . }}
{{/* This will give you an array of length 1, over which you then have to iterate. */}}
{{ $last_post := index $last_posts 0 }}
{{/* or */}}
{{ range $last_posts }}
{{/* last post here */}}
{{ . }}
{{ end }}
使用 Hugo len
按照相同的模式,您可以通过数组的长度获取最后一个索引。 Hugo's len function
{{ $last_index := (len .) - 1 }}
{{ last_post := index . $last_index }}
使用 CSS
您可以完全从模板中删除第一个和最后一个帖子的自定义处理,并使用 CSS 伪类,例如
所以你的帖子包装器可以有一个.posts CSS 类,然后,在你的样式表中,你可以有类似的东西
.posts:first-child {
/* first post, make it pop */
border-top: 1px dashed red;
}
.posts:last-child {
/* last post, make room */
border-bottom: 1px dashed black;
}
但是,通过这种方式,您可以将计算转移到客户端。我真的不认为这是一个密集的计算,尤其是只有第一个/最后一个,但这是需要考虑的事情。