Issue re: printf and variables

I’ve solved my problem a different way, so this is not blocking my work. However, it has caused me several hours of pain today, so wondering if anyone can shed some light on this.

Let’s say I have the following:

$x =   printf "%s" (print .Params.someparam "sometext")

Now let’s say the resultant $x provides the following text:

$s.somekey 

In the context of code such as the following:

{{- range $fname, $s := index .Site.Data.hosts -}}
{{- if eq $fname ($company) -}}

{{ $s.somekey }}

{{end}}
{{end}}

The problem is, that even though the command to retrieve the data "$s.somekey " renders as text, it simply prints the command rather than obtains the data.

I.e. you will get in the html:

$s.somekey 

Rather than:

"This is the data that was retrieved".

I am interested if anyone can shed some context on why this is?

Like I said, I resolved the issue by using:

{{- $x := printf "%s" (print .Params.someparam "sometext") -}}

{{ index .Site.Data.hosts $company $x }}

If I am understanding you correctly, could you do this instead?

{{- $x := .Params.someparam -}}

@zwbetz

That only provides part of the text for $x.

I am trying to access items in the data file within the range command. My code above was overly simplified, but lets give a more real example of one variation of code I tried

{{- range $fname, $s := index .Site.Data.hosts -}}
{{- if eq $fname ($companyid1) -}}
{{ (printf "$s.%sopinionsummary" ($.Params.typeid)) }}
{{end}}
{{end}}

For example, all that does is print:

$s.typeopinionsummary

Whereas the following code (when I add it manually), prints the data:

{{- range $fname, $s := index .Site.Data.hosts -}}
{{- if eq $fname ($companyid1) -}}
{{ $s.typeopinionsummary }}
{{end}}
{{end}}

I hope that clarifies it a little more.

Can you share your code repo? Or create a sample repo to where we can reproduce this?

1 Like

I’ll set up a sample repo tomorrow showing the issue.

Thanks

Sounds good.

In the meantime, see what this does (untested):

{{ $foo := (printf "$s.%sopinionsummary" $.Params.typeid) }}
{{ $foo }}

Yeh, that just produces the same:

$s.typeopinionsummary

Try this:

{{ $x := "somekey" }}

{{- range $fname, $s := index .Site.Data.hosts -}}
{{- if eq $fname ($company) -}}

{{ index $s $x }}

{{end}}
{{end}}
2 Likes

@moorereason

This helped a lot. I just had to remove the $s in the printf statement, and it worked like a charm.

{{- range $fname, $s := index .Site.Data.hosts -}}
{{- if eq $fname ($companyid) -}}

{{ $x :=  ( printf "%sopinionsummary" ($.Params.typeid) ) }}

{{ index $s $x }}

{{end}}
{{end}}

Thanks very much for your help on this.