Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display only 1 post from certain category with certain params "true"

Tags:

hugo

The idea is how to display only 1 latest post from certain category if it has params featured "true"

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

the code above is working but it render all the posts with category foo (more than 1 post)

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

the code above have no errors but it doesnt render at all

any clue?

like image 407
Yudy Ananda Avatar asked Oct 18 '25 17:10

Yudy Ananda


1 Answers

There is a way to solve this based on how categories is defined.

Solution (categories as a taxonomy)

In this case we will say it is a taxonomy, because categories is a default taxonomy if you do not specify any in your site config.

The first thing we do is get a collection of the pages that have a category with a value of photography

 {{ $photography := .Site.Taxonomies.categories.photography  }}

Then we have to find a way to get the pages that have featured true by using the function GroupByParam and group by featured

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

{{ end }}

The group within this range will return the .Key value of .Params.featured so we will check the value of each until it is true. After the group of featured is found, sort in the order you like and return the one (1) you want.

{{ if eq .Key true }}
  {{ range last 1 .Pages.ByDate }}
    // The `.` context here is a page. Use it accordingly
  {{ end }}
{{ end }}

Full Code Example (categories as a taxonomy)

{{ $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 }}

NOTES:

  • The solution uses ByDate to sort in order, but can use any valid page collection sorting to get the page you need using first or last accordingly.
  • Make sure the values in the grouped param (featured) are same type (boolean in this case). They will not work properly if they are mixed. They will work if you make them string, but need to check for string "true".
  • If you want to use taxonomy but not have the pages build for them you can disableKinds = ["taxonomy","taxonomyTerm"] in your config file as per Hugo docs.
like image 116
talves Avatar answered Oct 21 '25 18:10

talves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!