在Hugo中有条件地渲染多个部分

e0bqpujr  于 2023-04-03  发布在  Go
关注(0)|答案(1)|浏览(152)

我想呈现所有的markdown文件内的每个文件夹,除了静态一个在我的主页上的网站,这样做的一种方式是通过使用工会在雨果,但随着文件夹数量的增加,我看到自己重复工会各地(带有union的代码被注解了,这是顺便工作的),所以我想使用slice会是一个更好的主意,但是当我尝试使用slice时我得到以下错误-
无法呈现页面:渲染“home”失败:“(目录路径)\layouts\index.html:12:19”:执行模板失败于<.Pages>:无法计算字段字符串类型的页面
目录结构

index.html的代码

{{ define "main" }}
<ul class="homepage-topic-sections-container">
    {{$sectionNames := slice "posts" "problems" "tutorials"}}
    {{range $index, $sectionName := $sectionNames}}
    {{ range where .Pages "Section" $sectionName }}
    {{/*
    {{ range union (union
    (where .Pages "Section" "posts")
    (where .Pages "Section" "problems"))
    (where .Pages "Section" "tutorials")
    }}
    */}}
    <li>
        <section class="homepage-topic-section">
            <h1 class="topic-heading"><a href="{{.Permalink}}">{{.Title}} </a></h1>
            <div>
                {{ range .Pages }}
                <h3><a href="{{.Permalink}}">{{.Title}} &middot; {{.Date.Format "January 2, 2006"}}</a></h3>
                {{ end }}
            </div>
        </section>
    </li>
    {{end}}
    {{end}}

</ul>
{{ end }}
zd287kbt

zd287kbt1#

https://gohugo.io/templates/introduction/#the-dot:

Context(aka“the dot”)

关于Go模板,最容易被忽视的概念是{{ . }}总是引用当前上下文

  • 在模板的顶层,这将是可供其使用的数据集。
    • 但是,在迭代中,它将具有循环中当前项的值 *;即{{ . }}将不再指整个页面可用的数据。

在下面的代码中,.Pages中的点具有第一个range操作中的当前项的值。该值的类型是string,并且它没有字段Pages。这就是为什么它在execute of template failed at <.Pages>: can’t evaluate field Pages in type string中失败。

{{ define "main" }}
<ul class="homepage-topic-sections-container">
    {{$sectionNames := slice "posts" "problems" "tutorials"}}
    {{range $index, $sectionName := $sectionNames}}
    {{ range where .Pages "Section" $sectionName }}
                   ^^^^^^

一种可能的解决方法是使用$.访问全局上下文:.Pages ==〉$.Pages
也许更好的解决方案是列出排除部分。这样当添加更多文件夹时就不需要修改代码了:

{{ define "main" }}
<ul class="homepage-topic-sections-container">
    {{ range where .Pages "Section" "!=" "static" }}
    <li>

相关问题