如何仅显示特定类别中某些参数为“true”的 1 篇帖子

Yud*_*nda 4 hugo

这个想法是如何仅显示某个类别的 1 个最新帖子(如果它的参数为“true”)

{{ range (where .Data.Pages "Type" "blog") 1 }}  
{{ if and (in .Params.categories "photography") (in .Params.featured "true") }}
Run Code Online (Sandbox Code Playgroud)

上面的代码可以工作,但它会呈现类别为foo的所有帖子(超过 1 个帖子)

    {{ $photography := .Data.Pages.ByParam "categories"  }}
    {{ if and (in .Params.featured "true") (eq .Params.categories "photography") }}
       {{ range first 1 $photography }} 
Run Code Online (Sandbox Code Playgroud)

上面的代码没有错误,但根本不渲染

有什么线索吗?

tal*_*ves 7

有一种方法可以根据如何解决这个问题categories定义的方式来解决这个问题。

解决方案(类别作为分类法)

在这种情况下,我们会说它是一个分类法,因为categories如果您未在站点配置中指定任何分类法,则这是默认分类法。

我们要做的第一件事是获取类别值为 的页面集合photography

 {{ $photography := .Site.Taxonomies.categories.photography  }}
Run Code Online (Sandbox Code Playgroud)

true然后我们必须找到一种方法来使用函数GroupByParam和分组来获取具有特色的页面featured

{{ range ($photography.Pages.GroupByParam "featured") }}

{{ end }}
Run Code Online (Sandbox Code Playgroud)

该范围内的组将返回.Key的值.Params.featured,因此我们将检查每个组的值,直到为true。找到精选组后,按您喜欢的顺序排序并返回您想要的 (1) 个。

{{ if eq .Key true }}
  {{ range last 1 .Pages.ByDate }}
    // The `.` context here is a page. Use it accordingly
  {{ end }}
{{ end }}
Run Code Online (Sandbox Code Playgroud)

完整代码示例(类别作为分类法)

{{ $photography := .Site.Taxonomies.categories.photography  }}
{{ range ($photography.Pages.GroupByParam "featured") }}
  {{ if eq .Key true }}
    {{ range last 1 .Pages.ByDate }}
    // The `.` context here is a page. Use it accordingly
    {{ end }}
  {{ end }}
{{ end }}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 该解决方案使用ByDate按顺序排序,但可以使用任何有效的页面集合排序first来获取您需要使用或相应的页面last
  • 确保分组参数 ( featured) 中的值具有相同类型(在本例中为布尔值)。如果混合使用,它们将无法正常工作。如果你将它们设为 string ,它们就会起作用,但需要检查 string "true"
  • 如果您想使用分类法但没有为其构建页面,您可以按照 Hugo 文档disableKinds = ["taxonomy","taxonomyTerm"]在配置文件中进行配置。