Multiple lines in a statement

Hey,

So I don’t know Go other than using it within Hugo (explains my post history :sweat_smile:), but is it possible to implement multiple lines within a single statement in template files? That way we could have code blocks that would make things perhaps a bit more readable?

The best example I can think of would be the Image Processing shortcode from Hugo Docs:

{{ $original := .Page.Resources.GetMatch (printf "*%s*" (.Get 0)) }}
{{ $command := .Get 1 }}
{{ $options := .Get 2 }}
{{ if eq $command "Fit"}}
{{ .Scratch.Set "image" ($original.Fit $options) }}
{{ else if eq $command "Resize"}}
{{ .Scratch.Set "image" ($original.Resize $options) }}
{{ else if eq $command "Fill"}}
{{ .Scratch.Set "image" ($original.Fill $options) }}
{{ else }}
{{ errorf "Invalid image processing command: Must be one of Fit, Fill or Resize."}}
{{ end }}
{{ $image := .Scratch.Get "image" }}
<figure style="padding: 0.25rem; margin: 2rem 0; background-color: #cccc">
	<img style="max-width: 100%; width: auto; height: auto;" src="{{ $image.RelPermalink }}" width="{{ $image.Width }}" height="{{ $image.Height }}">
	<figcaption>
	<small>
	{{ with .Inner }}
	{{ . }}
	{{ else }}
	.{{ $command }} "{{ $options }}"
	{{ end }}
	</small>
	</figcaption>
</figure>  

We would be able to write it like this:

{{%
  $original := .Page.Resources.GetMatch (printf "*%s*" (.Get 0)) 
  $command := .Get 1 
  $options := .Get 2 
  if eq $command "Fit"
   .Scratch.Set "image" ($original.Fit $options) 
  else if eq $command "Resize"
   .Scratch.Set "image" ($original.Resize $options) 
  else if eq $command "Fill"
   .Scratch.Set "image" ($original.Fill $options) 
  else 
    errorf "Invalid image processing command: Must be one of Fit, Fill or Resize."
  end 
  $image := .Scratch.Get "image" 
%}}
<figure style="padding: 0.25rem; margin: 2rem 0; background-color: #cccc">
	<img style="max-width: 100%; width: auto; height: auto;" src="{{ $image.RelPermalink }}" width="{{ $image.Width }}" height="{{ $image.Height }}">
	<figcaption>
	<small>
	{{ with .Inner }}
	{{ . }}
	{{ else }}
	.{{ $command }} "{{ $options }}"
	{{ end }}
	</small>
	</figcaption>
</figure>  

Forgive me if this has been asked and answered, but I couldn’t find it.

Short answer: no.

Long answer still no, but with details. From: Introduction to Hugo Templating | Hugo :

A Single Statement Can be Split over Multiple Lines

{{ if or 
  (isset .Params "alt") 
  (isset .Params "caption")
}}

An if and an else are still separate statements, so your example code will largely stay as is.

As far as readability goes, indenting helps a lot.

1 Like

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