Do something different with last page in a loop

I’d like to create a one-line navigation with all featured pages

{{#get "pages" limit="all"}}
	{{#foreach pages}}
		{{#if featured}}
			<a href="{{url}}">{{title}}</a>&nbsp;&bull;
		{{/if}}
	{{/foreach}}
{{/get}}

But for the final page I don’t want to have the &nbsp;&bull; displayed. I am aware I could fudge this in CSS using an ::after and ::last-child but wondering if there is a way to do it within the loop

Thanks in advance!

When inside a foreach loop, you have access to special variables, including @last, which renders true when it’s the last item in the loop.

In the example below, it says, “If this item isn’t last, include the bullet.”

{{#get "pages" limit="all" filter="featured:true"}}
	{{#foreach pages}}
		<a href="{{url}}">{{title}}</a>{{^if @last}}&nbsp;&bull;{{/if}}
	{{/foreach}}
{{/get}}

I moved the featured check into the get helper, which is necessary for this to work correctly every time.

Thanks, that works perfectly :slight_smile:

1 Like