Hugo How to use a partial with parameters

Goal

I want to create a specific layout for some sample images I am showing in my main html page. As the layout is complex and I am intending to reuse it on other pages, I want to call a partial with some parameters :

  • the image path
  • a small description to show under the picture.

So the repeatable code will be in a file named snapimg.html in the partial folder.

Calling partial with Parameters

To call the partial code we can simply use a dictionary of key values. In the sample below, “img” and “title” are the keys.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

  ...
    <div class="d-flex">
      <div class="row row-cols-3 justify-content-md-center">
        {{ partial "snapimg.html" (dict "img" "/images/Italy.jpg" "title" "Italie" )}}
        {{ partial "snapimg.html" (dict "img" "/images/France.jpg" "title" "France" )}}
        {{ partial "snapimg.html" (dict "img" "/images/Belgium.jpg" "title" "Belgique" )}}
      </div>
    </div>
  ...

Using Parameters in Partial

to retrieve the value of the parameters in the partial html, simply use {{ .parameterName }}.

1
2
3
4
5
6
7
8
<div>
  <figure class="snap">
      <img  src="{{ .img }}" alt="{{ .title }}"  />
      <figcaption>
          {{ .title }}
      </figcaption>
  </figure>
</div>

References