Modifying frontmatter variables from hooks

Hi,
I try to compile a list of sources for all external references in a page.
I could parse the whole .RawContent with regexp but that’s too complicated.
A more intuitive way would be to set a variable like this:

Cascade:
- _target:
	kind: page
  Sources:
  - title: ""
    url: ""

For each page, than add to it (with the map function) from the image and link render hooks each time a remote ressource is encountered.
So I wrote {{.Param.sources = merge (dict "title" .PlainText "url" $destination) .Params.Sources}} here and there.
is it possible, and a good start ?

For now it says Error: add site dependencies: load resources: loading templates: "/home/drm/WEBSITE/themes/hugo-book/layouts/_default/_markup/render-image.html:23:1": parse failed: template: _default/_markup/render-image.html:23: unexpected "=" in operand, with the wrong line being one {{.Param.sources = merge (dict "title" .PlainText "url" $destination) .Params.Sources}}

This is not possible. You can’t change those values (as far as I know, if it’s possible it would be counter intuitive anyway. Everything you set in your frontmatter should be readonly to save you from confusion down the “layout-stack”.).

If you want to change and use the variable in the same layout file do this:

{{ $variable := merge (dict "title" .PlainText "url" $destination) .Params.Sources}} 

other stuff

Title: {{ $variable.title }}
Url: {{ $variable.url }}

Notes:

  • do you see the := in the first line? that is how you set a new variable.
  • I did not test if the merge command is correct, I just copied it from your sample.

If you want to create the value in one layout file and use in one that comes after this file, then look into the concept of scratches. A good introduction is here. (Note: this tutorial is around 5 years old. If anything does not work come back to this forum and link to the tutorial.)

The official documentation for scratch is here (follow the links on that page for additional information):

Oh yes, Scratch, I remember… ok, that seemed complicated but it is its intended use.
Thanks.

So to add a pair (title,url) I need to write:

{{ .Scratch.Add "Sources" (slice (dict "url" "$url" ".Text" ".Title")) }}

to then range over like this:

{{ range (.Scratch.Get "Sources")}}
{{ index . "title" }} : {{ index . "url" }}    --- doing stuff with
{{ end }}
{{ $sources := (.Scratch.Get "Sources") }}

How do I create a file to write in it from within hugo ?