Set frontmatter params in list template?


#1

All pages does not have weight params in frontmatter.
I want to set weight params in code based on file name.
File name format is xx_String.md.
xx is 2 digits.
So, I can get xx from bellow code, and hope to know //**//

 {{ range .Pages }}
        {{ $weight := substr .File.BaseFileName 0 2}}
       // * what method can I use for setting every page's weight with above value *//           
 {{ end }}   

If anyone have experiences on this, please let me know kindly…
Warm Regards.


#2

I don’t think you can set page-level variables in the front matter. But you can set page-scoped, writable variables using .Scratch

{{ range .Pages }}
  {{ $weight := substr .File.BaseFileName 0 2 }}
  {{ .Scratch.Set "weight" $weight }}         
{{ end }}  

Then, for example, if you wanted to print the weight of each page

{{ range .Pages }}
  {{ printf "%v" (.Scratch.Get "weight") }}
{{ end }}

#3

Yes.
Btw, I want to use this weight for the ordering.
That is my issue.
could you let me know about that.
Thanks.


#4

I don’t think what you want is currently possible in Hugo.


#5

If you prefix the file names with numbers, the ordering should anyways happen based on those numbers.

(I am already using that trick in one of my sites, though for menu names. I then remove the prefix numbers when displaying the menu name.)

If that doesn’t work, you can run a custom script before running Hugo that sets the weight in the file’s front-matter based on the file name prefix.


#6

Hi, Bep.
Thanks for your response.
Then, how can I order list based on filename?
Is it possible?


#7

Thanks, Kaushalmodi.

Could you let me know specific samples?


#8

Here’s a sample script. You’d run this in the same directory that has the content files you want edited. What it does:

  • Loops through all .md files in the directory
  • Sets a weight var with the first 2 chars of the filename
  • Calls an awk program that inserts the weight: xx into the front matter, right above the last ---
  • It then overwrites the file with the new changes

This assumes yaml for your front matter. If you use toml, you’ll need to adjust this script accordingly.

#!/bin/bash

for file in *.md; do
    weight=${file:0:2}
    awk -v weight=$weight '/---/{
        count++
        if(count == 2){
        sub("---","weight: " weight "\n---",$0)
        }
    }
    {print}' $file > tmp && mv tmp $file
done

Then you should be able to do

{{ range .Pages.ByWeight }}
<!-- some code -->
{{ end