Hugo 如何在 terms.html 中对标签和类别进行排序

发布于 2025-01-15 20:08:55 字数 424 浏览 2 评论 0原文

按照文档,我有我的 layouts/_default/terms.html 模板,如下所示:

{{ range .Pages }}
<li>
    <a href="{{ .Permalink }}">{{ .Title }}</a>
</li>
{{ end }}

我的标签或类别(取决于我是否在 /tags//categories/)列出所有标签/类别,但不按字母顺序排列。

如何对它们进行排序?我尝试添加像 {{ range sort .Pages }} 这样的 sort 关键字,但它不起作用。知道如何按 .Title 对它们进行排序吗?

Following the documentation, I have my layouts/_default/terms.html template which looks like this:

{{ range .Pages }}
<li>
    <a href="{{ .Permalink }}">{{ .Title }}</a>
</li>
{{ end }}

My tags or categories (depending on if I'm on /tags/ or /categories/) list all the tags/categories but not in alphabetical order.

How to sort them ? I have tried to add the sort keyword like this {{ range sort .Pages }} but it doesn't work. Any idea how to sort them by .Title ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟酉 2025-01-22 20:08:55

您需要为 sort 函数指定排序属性。由于您正在迭代标签页面列表,因此您可能想要使用页面的标题(即标签名称):

{{ range (sort .Pages "Title") }}
<li>
    <a href="{{ .Permalink }}">{{ .Title }}</a>
</li>
{{ end }}

同样,如果您想对作为参数传递的标签进行排序,您可以这样做:

{{ range  (sort .Params.tags) }}
<li class="tag-{{ . }}">
    <a href="{{ "tags/" | absLangURL }}{{ . | urlize }}">{{ . }}</a>
</li>
{{ end }}

如果如果您希望列表的顺序相反,请将“desc”作为第三个参数传递给 sort 函数。

You need to specify the property to sort on to the sort function. Since you're iterating over a list of tag pages, you probably want to use the titles of the pages (which are the tag names):

{{ range (sort .Pages "Title") }}
<li>
    <a href="{{ .Permalink }}">{{ .Title }}</a>
</li>
{{ end }}

Similarly, if you want to sort tags passed as Params, you can do that like so:

{{ range  (sort .Params.tags) }}
<li class="tag-{{ . }}">
    <a href="{{ "tags/" | absLangURL }}{{ . | urlize }}">{{ . }}</a>
</li>
{{ end }}

If you want the list to be in the opposite order, pass "desc" to the sort function as the third argument.

猫卆 2025-01-22 20:08:55

减少混乱:

{{range .Pages.ByTitle}} 
<li>
    <a href="{{ .Permalink }}">{{ .Title }}</a>
</li>
{{ end }}

文档: https://gohugo.io/templates/lists/#by-title

Less clutter:

{{range .Pages.ByTitle}} 
<li>
    <a href="{{ .Permalink }}">{{ .Title }}</a>
</li>
{{ end }}

Docs: https://gohugo.io/templates/lists/#by-title

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文