[SOLVED] Is there a better way to write loops in loops?

I’m coming from a PHP/WP background so trying to make sense of the template language is like making sense of hieroglyphics.

Is there a better way to loop through the same block of code for pages and the home page?? Example:

{{ if .IsHome }}
      {{ range first 1 (where .Data.Pages "Type" "poetry") }}
        {{ if isset .Params "js" }}
        {{ range .Params.js }}
            <script src="{{ . }}"></script>
            {{ end }}
        {{ end }}
      {{ end }}
    {{ else }}  
      {{ if isset .Params "js" }}
        {{ range .Params.js }}
            <script src="{{ . }}"></script>
            {{ end }}
        {{ end }}
    {{ end }}

Looking at this feels extremely messy and unreadable and I feel like there must be something I’m missing to make this easier to understand. Halp. :frowning:

I would just with with instead of if + isset wherever possible. So:

{{ if .IsHome }}
    {{ range first 1 (where .Data.Pages "Type" "poetry") }}
        {{ with .Params "js" }}
            {{ range . }}
                <script src="{{ . | safeJS }}"></script>
            {{ end }}
        {{ end }}
    {{ end }}
{{ else }}
    {{ with .Params "js" }}
        {{ range . }}
                <script src="{{ . | safeJS }}"></script>
        {{ end }}
    {{ end }}
{{ end }}

PS: You might also need the safeJS as I have shown in my version of your snippet.

2 Likes

Thank you SO MUCH for the quick reply!
I keep forgetting there is a with function; it never crossed my mind since I’m so used to thinking in ifs and ors. I will look into safeJS, thank you for letting me know about it.

Also, first returns a slice. If you only care about the first page returned by that where, you can alternatively do:

{{ with (index (where .Data.Pages "Type" "poetry") 0) }}
3 Likes

Oh that is good to know, I assume you can change the 0 to whatever number post you want to return as well? For example if I wanted to return the 3rd post I’d change the 0 to a 3?

No, 2. Counting begins at 0 :slight_smile:

2 Likes

Right. :joy: Thank you thank you thank you!