Skip to content

Commit

Permalink
[bugfix] Let templates deref pointers, as a treat (#2448)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsmethurst committed Dec 12, 2023
1 parent ac48192 commit d0bb8f0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
15 changes: 15 additions & 0 deletions internal/router/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"html/template"
"os"
"path/filepath"
"reflect"
"strings"
"time"
"unsafe"
Expand Down Expand Up @@ -180,6 +181,19 @@ func isNil(i interface{}) bool {
return (*eface)(unsafe.Pointer(&i)).data == nil
}

// deref returns the dereferenced value of
// its input. To ensure you don't pass nil
// pointers into this func, use isNil first.
func deref(i any) any {
vOf := reflect.ValueOf(i)
if vOf.Kind() != reflect.Pointer {
// Not a pointer.
return i
}

return vOf.Elem()
}

func LoadTemplateFunctions(engine *gin.Engine) {
engine.SetFuncMap(template.FuncMap{
"escape": escape,
Expand All @@ -194,5 +208,6 @@ func LoadTemplateFunctions(engine *gin.Engine) {
"acctInstance": acctInstance,
"increment": increment,
"isNil": isNil,
"deref": deref,
})
}
8 changes: 5 additions & 3 deletions web/template/status_poll.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,17 @@
{{- if isNil $pollOption.VotesCount }}
Results not yet published.
{{- else -}}
{{- with deref $pollOption.VotesCount }}
<span class="poll-vote-share">{{- $pollOption.VoteShareStr -}}&#37;</span>
<span class="poll-vote-count">
{{- if eq $pollOption.VotesCount 1 -}}
{{- $pollOption.VotesCount }} vote
{{- if eq . 1 -}}
{{- . }} vote
{{- else -}}
{{- $pollOption.VotesCount }} votes
{{- . }} votes
{{- end -}}
</span>
{{- end -}}
{{- end }}
</div>
</li>
{{- end }}
Expand Down

0 comments on commit d0bb8f0

Please sign in to comment.