Create a custom id for each post

yea, it would be great if someone could help me on this, i read & search but still couldn’t find the answer this couple of days, maybe i’m still quite noobs in go.

what I want is, to create custom unique id for each div in post loop in the template, because i have a pop-up modal for each post.

what i usually do in php is just declare $i = 1; outside the loop, then in the loop just use
<div id="hidden<?php echo $i++; ?>" >
so it have unique id for each post

i tried with adding variable like this outside the loop
{{ $unique := 1 }}
then in the loop add this
{{ add $unique 1 }}
but the variable just echo 2 and doesnt add up for each post.

am i missing something here? i also try throw the $unique var to new var but still it just echoing same sum.

1 Like

I’m no expert on this, but have been bitten with scoping issues similar to this in the Go templates.

If you build and use 0-13-DEV you can use

{{ .UniqueId }}

Which is a MD5 hash of the filename + path.

3 Likes

Of course, if a counter is good enough, then something like this would also work (top 10 pages by length):

{{ range $index, $page := first 10  .Data.Pages.ByLength.Reverse }}
      {{ add $index 1 }}. {{ $page.Title }}<br/>
{{ end }}

Note, all sorting in Go is Stable (i. e. not randomly changing)

3 Likes

Awesome! it works :slight_smile: thanks for the help

Ha! The unique ID was introduced to protect footnotes on list pages, and it would exactly help with what you need here. Unintended benefits, who knew?

Does this variable still work in 0.14? If I use it in single.html, I don’t get an error message but it breaks the generation of the page (below .UniqueId, no content is generated).

Edit: Nevermind, found on Github that it’s called UniqueID now. Just keep my post here in case someone else also runs into this.

1 Like

According to the documentation, {{ .UniqueId }} is now deprecated and should be replaced by {{ .File.UniqueID }}

Please also note that files with similar names (but in different folders) may have the same UniqueID (using .File.UniqueID may fix this issue, not sure, the ticket is not clear on this point)