Assign or override a page parameter

I want to assign the weight of a page on build from a template in layouts. I additionally want to create a new page parameter chapter.

I have the logic to extract the value of weight and chapter working fine. They are stored in $weight and $chapter. Printing them yields expected values.

When I try to do

{{ default $chapter .Params.Chapter }}

{{ printf "%#v" .Params.Chapter }}

I get the value <nil> printed.

Similarly for weight, I get the value 0 printed instead of what I wanted to assign.

How can assign a value to a page parameter or override a pre-existing value (as is the case of weight) if necessary?

Note: I am aware that there are multiple threads on this topic. Trying whatever threads I found did not work.

Do you mean you want to assign a page variable from a template file? You are not able to this. You can assign it to a page’s .Scratch, but you cannot update the page variable directly.

Doc: .Scratch | Hugo

I do want to assign a page variable. This variable will be used like the page’s title.

Am I right in assuming that I cannot create a new variable for this use?

Can I atleast override an existing variable like weight?

{{ $chapter := .Params.Chapter | default "Default Chapter" }}

Thank you. I will try it when I get the time.

Also see Front Matter | Hugo

@bep , your solution did not work for me for some reason. When I try to printf .Params.Chapter, I get nil.

You need to print the variable $chapter. To set default ´.Params`, see my last link.

@bep, I think you misunderstood me. (Or I misunderstood you:))

I already have assigned $chapter; I extract it from the title. Since this data is already available in the title, I don’t want to manually enter it into the front matter. The value is not the same from post to post.
If it was, I would have used the cascading front matter.

Rather, I am trying to assign the chapter by extracting it using findRE and then assigning it.
I am trying to do a similar assignment with the post’s weight.

Is it possible to do anything like this?

Thanks for all the help so far!

You cannot change a frontmatter variable value from the layout.

Marking as solved then.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.