Transform a string variable into the variable itself

Sorry, I do not have the vocabulary to describe (or search for) this properly:

I have a string variable $command with a value like for instance .IsHome. Is there ANY way in gotemplates to transform it into its variable equivalent inside of a template?

For instance:

{{ $variable := ".IsHome" }}
{{ range $pages }}
  {{ $$variable }} <-- echoes the value of .IsHome inside of the current page object
{{ end }}

In PHP I think that’s called a variable variable. You define the variablename with $variable and get the variable with that name using $$variable.

Is that possible within Hugo (or Go itself)?

layouts/partials/eval.html

{{ $f := printf "%d.txt" now.UnixNano }}
{{ $r := printf "{{ %s }}" .cmd | resources.FromString $f }}
{{ $r = $r | resources.ExecuteAsTemplate $f .ctx }}
{{ return $r.Content }}

template

{{ $variable := ".IsHome" }}
{{ partial "eval" (dict "ctx" . "cmd" $variable) }} --> true/false

{{ $cmd := "add 5 1" }}
{{ partial "eval" (dict "ctx" . "cmd" $cmd) }}  --> 6
1 Like

Perfect. ExecuteAsTemplate makes much more sense now.

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