我正在使用此baseof.html
将first-post
类添加到body标签,以便可以在分页的一系列文章的第一篇文章中使用特定的CSS:
<body class="
{{ with where site.RegularPages "Type" "posts" }}
{{ $first_post = index . 0 }}
{{ if eq $first_post $ }}
first-post
{{ end }}
{{ end }}
">
但是如何为上一篇文章添加课程?这样,我收到错误“无法遍历* hugolib.pageState”:
<body class="
{{ with where site.RegularPages "Type" "posts" }}
{{ $last_post := last 1 $ }}
{{ if eq $last_post $ }}
last-post
{{ end }}
{{ end }}
">
LE:我重新阅读了您的问题,并意识到最初我误解了您的目标。我已重做答案,希望这次能正确解决。
为了在迭代项目时向项目添加CSS
类,即在同一页面上显示多个,我在下面保留了旧答案。
要在项目自己的页面上添加类,请根据其在全局列表中的位置进行尝试。
将$allPosts
中的项目取整。默认情况下,我认为它们按.Date
降序排列,即最新的。要强制执行自己的订单或条件,可以使用sort
。
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 }}
之类的模板中,该模板在每个页面上运行。因此,对于呈现的每个页面,您都需要进行最后检查,以查看当前页面是否为特殊页面之一。
我不知道Hugo这么说是不是有比较两页的更好方法,但是single.html
似乎足够好。
.Permalink
显示整个列表,以便可视化什么。
{{ 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中是这样的话。实际上,这可以解释该错误。 $
期望第二个参数是一个数组,并且您给它一个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's len
function
您可以从模板中删除首个和最后一个帖子的自定义处理,并使用CSS伪类,例如
len
{{ $last_index := (len .) - 1 }}
{{ last_post := index . $last_index }}
因此您的帖子包装器可以有一个:first-child()
CSS类,然后在样式表中可以有类似的东西
:first-child()
但是,通过这种方式,您可以将计算移交给客户端。我真的不认为这是一项密集的计算,尤其是仅使用第一个/最后一个时,但这是需要考虑的事情。