Using Partial files as functions
To avoid repeating some code, we can use partial files to create a function that returns a value.
Returning a value vs just including a partial
Returning a value is useful when you want to pass a variable from a partial to the layout. Since partials are scoped, it’s not so easy to do this. We would have to use .Scratch
to pass a value to the outer template.
Returning a value is most useful when you’ll need to have more control over the partial file’s output on a case-by-case basis. In this featured image example, I’ll likely embed a featured image in different areas on the site with different formatting/layout requirements. I’ll probaby vary the markup surrounding the image. As a result, I wouldn’t want to have to add many conditions to my partial file to account for all the different potential layouts.
In this case, we’ll create a partial file that allows us to return an image that is resized.
- In the layout file, I’ll reference the partial. I’m using
dict
to pass the page context (the.
) and I’ve also added a parameter called “size” so that I can define the image size on a case-by-case basis.{{ partial "helpers/featured_image.html" (dict "page" . "size" "250x" ) . }}
// in helpers/featured_image.html
{{ with .page.Params.grid_item.background_image }}
{{ $imageResource := ($.page.Site.GetPage "section" "uploads").Resources.GetMatch (strings.TrimPrefix "/uploads/" . ) }}
{{ $size := $imageResource.Resize "250x q100" }}
{{ with $.size }}
{{ $size = print . " q100" }}
{{ $size = $imageResource.Resize $size }}
{{ end }}
{{ $image = $size }}
<img src="{{ $image.Permalink }} />
{{ end }}
- Now, I’ll adjust the partial to return just the image resource. To avoid build errors, set the value to false at the beginning of your partial.
// in helpers/featured_image.html
{{ $image := false }}
{{ with .page.Params.grid_item.background_image }}
{{ $imageResource := ($.page.Site.GetPage "section" "uploads").Resources.GetMatch (strings.TrimPrefix "/uploads/" . ) }}
{{ $size := $imageResource.Resize "250x q100" }}
{{ with $.size }}
{{ $size = print . " q100" }}
{{ $size = $imageResource.Resize $size }}
{{ end }}
{{ $image = $size }}
{{ return $image }}
{{ end }}
Replace <img>
with the return statement.
- I’ll update the layout file to use
with
, which will allow us to return the value from within the partial.
// in layout
{{ with partial "helpers/featured_image.html" (dict "page" . "size" "250x" ) . }}
// {{ . }} = $image
<img src="{{ .Permalink }}" />
{{ end }}
You can access the returned value from the partial between the with statement with {{ . }}
.