Is possible to read page variables dynamically

Something like the follows.

{{/* $var is dynamic, description, date */}}
{{ $var := "title" }}
{{ with index . $var }}
  ...
{{ end }}

Error as follows, is there a workaround to do that?

can’t index item of type hugolib.pageState

actually

  • the page object is not an object or a simple map but some internal representation
  • the fields you want to access are not fields but methods

I’m not aware of a functionality to directly call a named method.

What you could do:

  • Create your own map and then index

     {{ warnf "======== static =============" }}
     {{ $pageFields := dict "Draft" .Draft "Name" .Name "Description" .Description "Date" .Date "Title" .Title }}
     {{ warnf "MAP INDEX %s = %v" "Title" (index $pageFields "Title") }}
     {{ range $k, $v := $pageFields }}
        {{ warnf "MAP RANGE %s = %v" $k $v }}
     {{ end }}
    
  • dynamically create a map from the Page object and access the fields

    ONLY for debugging !!! may change anytime

    {{ with transform.Unmarshal (debug.Dump .) }}

Thanks, those approaches would slow down build performance, it would better if I can avoid creating new variables to store duplicate data, but as you said, it may impossible.

The above is possible, but not all page variables will be in that map.

What about that one using apply

{{ $arg := "site.Title" }}
{{ $val := index (apply (slice "noop") $arg) 0 }}
{{ warnf "Value of %s is %s" $arg $val }}

{{ $arg = "page.Title" }}
{{ $val = index (apply (slice "noop") $arg) 0 }}
{{ warnf "Value of %s is %s" $arg $val }}

{ $arg = "Title" }}
{{ $val = index (apply (slice "noop") (print "page.%s" $arg)) 0 }}
{{ warnf "Value of %s is %s" $arg $val }}

 

These are clever:

{{ index (apply (slice 0) "page.Title") 0 }}
{{ index (apply (slice 0) "site.Title") 0 }}

But this will not will work:

{{ range .Pages }}
  {{ index (apply (slice 0) "page.Title") 0 }}
{{ end }}

https://gohugo.io/functions/global/page/#warnings

Thank you all very much :heart:, will try later.

Thanks a lot, summary it up here, hope it helps others.

Get Dynamic Variable Of Page

{{ $var := "page.Title" }}
{{ index (apply (slice 0) $var) 0 }}

Get Dynamic Params Of Page

The above approach can not used to get parameter, since parameter value isn’t a function, please use the below approach instead.

{{ with index .Params $param }}