Right now I am using a front matter value called with .Params
. But is there a better way to range over a nested section with where
?
The context of your question is unclear, but from any page you could do:
{{ $section := "/foo/posts/" }}
{{ with .GetPage $section }}
{{ range .Pages }}
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}
{{ else }}
{{ errorf "Unable to find %s" $section }}
{{ end }}
To limit the output to pages with a specific param value:
{{ $section := "/foo/posts/" }}
{{ with .GetPage $section }}
{{ range where .Pages "Params.foo" "bar" }}
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}
{{ else }}
{{ errorf "Unable to find %s" $section }}
{{ end }}
content/section/nested-section/_index.md
---
title: Posts
url: "post"
cascade:
id: posts
---
{{ range where site.RegularPages ".Params.id" "posts" }}
<!-- code goes here -->
{{ end }}
That’s how I do it. I was asking if there is a more elegant way to do it. Or even excluding certain nested sections instead of doing ".Params.id" "ne" "posts"
if there are more nested sections.
Cascading a section/subsection identifier seems like a bit of a hassle.
To avoid that, you could do something like:
{{ $sectionPaths := slice
"section/nested-section/"
"foo/bar/baz/"
}}
{{ range $sectionPath := $sectionPaths }}
{{ with $sectionPage := page.GetPage $sectionPath }}
{{ range site.RegularPages }}
{{ if .InSection $sectionPage }}
<h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }}
{{ end }}
{{ else }}
{{ errorf "Unable to find %s" $sectionPath }}
{{ end }}
{{ end }}
Uses the page
function, so needs v0.111.1. If you haven’t upgraded yet, replace page
with $
.
This seems a bit complex than what I had in mind. But let me study it and see how to edit my templates to cater for it. Thanks.
@jmooring is there a downside to using my method of cascading? I find it easier to grasp and it’s less code. Or what do you mean by ‘hassle’? (I think as a few others have pointed in this forum, I wish nested sections had more support like sections do. )
Yeah, but you write the code once, parameterize it, and call it as a partial when you need it.
Compare that to maintaining front matter, which I find to be error-prone.
I never thought of using it as a partial. Now that makes more sense. Let me test a few templates.
Last questions, is .GetPage
the correct way to target a nested section, e.g. for loading certain assets? I already assume I can use the same method you shared to target the pages themselves in that nested section.
If I understand your question correctly, yes. Once you have the page reference you can get any property of the page, and use any of the page methods, including .ResourcesGet
or whatever.
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.