Is it possible to capture template output into a variable?

In jekyll’s liquid you can {% capture varname %}content{% endcapture %} to assign arbitrary template output to a variable. Is there some equivalent in hugo? SO from 2020 suggests not

Do you want to return a value from a partial ?

Nope. I was thinking more like rendering several snippets (Through partials or otherwise) to a newScratch list and then looping through them. If I returned a string from a partial I’d still need a way to “Record” the string to be passed to return

templates

layouts/partials/
├── a.html
└── b.html

template

{{ $s := newScratch }}
{{ $p := slice "a" "b" }}
{{ range $p }}
  {{ $s.SetInMap "renderedPartials" . (partial (printf "%s.html" .) .) }}
{{ end }}

<pre>{{ jsonify (dict "indent" "  ") $s.Values }}</pre>

result

{
  "renderedPartials": {
    "a": "\u003cp\u003eThis is layouts/partials/a.html\u003c/p\u003e\n",
    "b": "\u003cp\u003eThis is layouts/partials/b.html\u003c/p\u003e\n"
  }
}

Huh, that gave me an idea

{{ $s := newScratch }}

{{ define "x" }}
Arbitrary
<p>HTML</p>
Here
{{ end }}

{{ $s.Set "test" (template "x" .) }}

Unfortunately define has to be used at the top level and template can’t be used in parentheses like partial. Good to know though, thanks

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