雨果:我怎样才能为最后一篇文章添加一个类



我使用这个baseof.htmlfirst-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 }}
">

last的文档:https://gohugo.io/functions/last/

LE:我重读了你的问题,意识到我最初误解了你的目标。我已经重做了答案,希望这次我做对了

为了在迭代CSS类的同时将它们添加到项目中,即在同一页面上显示多个,我保留了下面的旧答案。

要在项目自己的页面上添加类,请根据其在全局列表中的位置进行尝试。

列表&排序

$allPosts中的项目取整。默认情况下,我认为它们按.Date排序,降序排列,即最新的第一位。要强制执行自己的订单或标准,可以使用sort

{{ $allPosts := where site.RegularPages "Type" "posts" }}
{{ $allPostsByDate := sort $allPosts ".Date" "asc" }}

感兴趣的页面

买哪种特别的。对于第一个和最后一个,您可以使用它们各自的内置功能;firstlast都返回一个元素(在本例中为页面(的数组,因此要提取一个元素,可以使用index

{{ $firstPost := index (first 1 $allPostsByDate) 0 }}
{{ $lastPost := index (last 1 $allPostsByDate) 0 }}

与当前页面比较

本例中的所有代码都必须包含在像single.html这样的模板中,该模板针对每个页面运行。因此,对于渲染的每个页面,您都要进行最后一次检查,以查看当前页面是否是特殊页面之一。

我不太了解Hugo,不知道是否有更好的方法来比较两页,但.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 }} &mdash;
{{ 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的len函数

{{ $last_index := (len .) - 1 }}
{{ last_post := index . $last_index }}

使用CSS

您可以从模板中完全删除第一篇和最后一篇文章的自定义处理,并使用CSS伪类,如

  • :first-child()
  • :last-child()

所以你的posts包装器可以有一个.postsCSS类,然后,在你的样式表中,你可以有类似的东西

.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;
}

但是,通过这种方式,您可以将计算转移到客户端。我真的不认为这是一个密集的计算,尤其是只有第一个/最后一个,但这是需要考虑的。

最新更新