Defining custom variables

I have different pages that will use the same search form, but sorted differently using different custom variables. How do I achieve this without copy pasting the search form code multiple times between if-else? I will be using .RelPermalink to distinguish the variables to use, e.g

{{- if eq .RelPermalink "/search/"}}
{{- $pages := where site.RegularPages "Type" "post"}}
{{- else if eq .RelPermalink "/search/news/"}}
{{- $pages := where site.Pages "Section" "news"}}
{{- end }}

search form HTML code goes here

(This example does not work since Hugo throws an error that $pages is not defined)

if creates a scope. Your $pages variable is going out of scope right after you create it.

Do it this way to define $pages outside the conditional.

{{- $pages := slice -}}
{{- if eq .RelPermalink "/search/"}}
{{- $pages = where site.RegularPages "Type" "post"}}
{{- else if eq .RelPermalink "/search/news/"}}
{{- $pages = where site.Pages "Section" "news"}}
{{- end }}
1 Like

Thanks! This makes the code tidier.

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