How to set variable inside range but access outside

On every page I want to implement a specific file (this could be an icon, a hero image or whatever).

I want to raise an error if there is no file for a specific page.

To implement this feature I need to set a variable inside a range (set variable to true if file was found) and then access the variable outside the range (check if file was found).

How can I do that?

{{ range readDir "static/icons" }}
{{ if (findRE $pattern .Name 1) }}
{{ $icon := true }}
{{ end }}
{{ end }}

{{ if not $icon }}
{{ errorf "Icon doesn't exist for page %q" .Path }}
{{ end }}
{{ $icon := false }}
{{ range readDir "static/icons" }}
{{ if (findRE $pattern .Name 1) }}
{{ $icon = true }}
{{ end }}
{{ end }}

{{ if not $icon }}
{{ errorf "Icon doesn't exist for page %q" .Path }}
{{ end }}

** note the difference between := and =

4 Likes

Wow! That was easy.

I read through the docs but I missed this one :grimacing:

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