如何通过 Hugo 页面的 Markdown 名称进行迭代?

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

How to iterate through hugo pages by markdown names

问题

我正在构建一个简单的Hugo博客,并且我有以下的toml配置用于一个页面:

+++
[publications]
links = ["2017/article1",
        "2017/article2"]
+++

我在相应的内容部分(content/publications/2017/article1.md)有这些文件。我需要遍历它们,加载每个页面,并在构建一个部分时使用它们的一些.Params。类似于:

 {{ range .Params.publications.links }}
 {{ 使用页面参数做一些操作 }}
 {{ end }}

我猜这是一个基本的Hugo问题,我只是无法弄清楚。

英文:

I am building a simple Hugo blog and I have this following toml config for a page

+++
[publications]
links = ["2017/article1",
        "2017/article2"]
+++

And I have these files in their appropriate content section (content/publications/2017/article1.md). What I need is to iterate through them, load each page and use some of their .Params in building a partial. Something like

 {{ range .Params.publications.links }}
 {{ do something with page parameters }}
 {{ end }}

I guess it is a basic Hugo question, I just cant figure it out.

答案1

得分: 6

这实际上需要对Hugo模板进行一些相当高级的使用。但是你是可以做到的!

首先,为了方便起见,将“.md”扩展名添加到你要访问的页面上。最好还要添加完整路径,这样如果将来在不同目录中添加具有相同名称的文件,Hugo就不会获取错误的文件。

+++
[publications]
links = ["publications/2017/article1.md",
        "publications/2017/article2.md"]
+++

然后你可以在模板中使用以下内容。

{{ range .Params.publications.links }}
  {{ range where $.Site.Pages "URL" ($.RelRef .) }}
    “{{ .Title }}”页面有{{ .WordCount }}个字。
  {{ end }}
{{ end }}

这里使用了where函数来通过URL字段过滤所有站点页面的数组。为了找到URL,它使用了带有链接文本的.RelRef页面变量

我认为还应该有一种使用apply函数来完成这个任务而不需要内部的range语句的方法,但是我无法让它正常工作。

英文:

This actually requires some pretty advanced use of Hugo templates. But you can do it!

First, to make it easy for yourself, add the ".md" extension to the pages you are trying to access. It's probably also a good idea to add the full path so that Hugo doesn't get the wrong file if you add files with the same name in a different directory in the future.

+++
[publications]
links = ["publications/2017/article1.md",
        "publications/2017/article2.md"]
+++

Then you can use something like the following in your template.

{{ range .Params.publications.links }}
  {{ range where $.Site.Pages "URL" ($.RelRef .) }}
    The "{{ .Title }}" page has {{ .WordCount }} words.
  {{ end }}
{{ end }}

This uses the where function to filter the array of all the site's pages by the URL field. To find the URL it uses the .RelRef page variable with the link text.

I think there should also be a way to use the apply function to do this without the inner range statement, but I couldn't get it to work.

huangapple
  • 本文由 发表于 2017年4月17日 02:37:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/43440708.html
匿名

发表评论

匿名网友

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

确定