Render to a variable

I was wondering about if is not possible to render Hugo templates to a variable without using partials.

Now, I know it is possible to do something like:
{{ $someContent := partial "some-partial" }}

What I would like to accomplish is to permform almost the same operation, but in the same file, avoiding the creation of meaningless partials.

Something like:

{{ $someContent := capture }}
  <p>Any content, {{ .here }}.</p>
{{ end }}

A sample using this: store content into col1 and col2. Then, then I can easily control the rendering order by simples using a .reverse property.

Edit: this is a very common operation when using ReactJS.

Thank you

You could try using templates like in the breadcrumbs example here:

That will do!

I could be better, but at least this is good enough for my use case.
I was looking for this command some time ago.

I can’t do that:

{{ $content := template "some-template" . }}
{{ $content }} 
{{ $content }}

But at least I can call the same template multiple times, keeping my code DRY.

{{ template "some-template" . }}
{{ template "some-template" . }}

Thank you so much!

Note that the soon to come Hugo 0.55 also supports a new return keyword in the partial templates, which may or may not be helpful in your case.

1 Like

Hum, it will not help in this particular case. Only if the same functionality will be available in the define/template.

Anyway, this sounds very cool!

I can think of some scenarios where it would be very useful.

I finally can return a dict instead of passing a Scratch to a partial.

I also can return other primitive types different from strings.

I’m looking forward for the new version. Thank you for the info!

1 Like