How to use `printf` with `apply`?

I want to format all strings in a slice of maps. I think apply is what I need but I can’t wrap my head around it.

This is my attempt:

{{ apply $slice "printf" "%s %s %s" ".social.github" ".social.facebook" ".social.discord" }}
{{ apply (slice "a" "b") "warnf" "%s" "." }}

prints out “a” and “b” on the console.
So without further information on

  • what your intended outcome is and
  • what $slice contains and
  • what your attempt results in (error message? no output?)

I don’t know what else to tell you. Oh, btw: the doc states that "." in the function’s argument list refers to the current element in the collection (i.e. $slice) here. You do not even use ".", so why the $slice et all?

My slice is as follows:

- key1:
    social:
      github: bla bla
      facebook: bla bla
      discord: bla bla
- key2:
    social:
      github: bla bla
      facebook: bla bla
      discord: bla bla

I want to fill these values in a string. For example,

"My GitHub profile is %s. My facebook profile is %s. You can find me on discord at %s."

My attempt:

{{ apply $slice "printf" "%s %s %s" ".social.github" ".social.facebook" ".social.discord" }}

It prints ".social.github .social.facebook .social.discord" for each element as a string, and doesn’t evaluate the slice fields.

I wouldn’t use apply here. You have an slice of maps of maps. That’s too much for apply to handle. Use range instead.

1 Like

Please read the end of my answer and the documentation regarding the use of “.”
You’re not iterating over your slice!

1 Like

Yeah, I would do it too. But though a one liner would be better in the LaTeX template I was generating with Hugo, where I was trying to avoid escaping characters.

I’m not 100% clear if this will help, but with the following frontmatter:

social_slice:
    - key1:
        social:
            github: blaha
            facebook: blahb
            discord: blahc
    - key2:
        social:
            github: blaha2
            facebook: blahb2
            discord: blahc2

What I show below gives:

  • github blaha facebook blahb discord blahc
  • github blaha2 facebook blahb2 discord blahc2

The first thing you need is a partial which you apply the slice of maps to (that is it gets key1, key2, etc):

/layouts/partials/social_group.html

{{ range . }}
    <li>
        {{ printf "github %s facebook %s discord %s" .social.github .social.facebook .social.discord }}
    </li>
{{ end }}

Then you can have something like (e.g in your LaTeX template):

<ul>
{{ range (apply (.Page.Params.social_slice) "partial" "social_group" ".") }} {{ . }} {{ end }}
</ul>

where obviously you won’t use the <ul> or <li> tags since it’s for LaTeX.

HTH.

The important thing to realize is apply returns a slice. You may want to use delimit to ‘de-slice’ instead of ranging.

That would look like:

<ul>
{{ delimit (apply (.Page.Params.social_slice) "partial" "social_group" ".") " " }}
</ul>