Im newbie in golang code as well as in gin gonic. I got a problem while using gin gonic.
In my controller. i get all articles and render to html file by code.
c.HTML(http.StatusOK, "articles/list", gin.H{
"title": "Articles",
"articles": articles,
})
and articles have field "CreatedOn" type int64 (created date) So in my view list.html, how i can parse CreateOn type int64 to date format.
<div class="list-group">
{{ range $article := $articles }}
<a href="/articles/{{ $article.Id }}" class="list-group-item">
<h4 class="list-group-item-heading">{{ $article.Title }}</h4>
<p class="list-group-item-text">{{ $article.Body }}</p>
<p class="list-group-item-text">{{ $article.CreatedOn }}</p>
<p class="list-group-item-text"></p>
</a>
{{ end }}
</div>
Thanks all
I had found a way that i write a method FormatDate()
func (a *Article) FormatDate(ab int64) string {
return "test Time"
}
in model "Article". then in my view i call
<p class="list-group-item-text">{{ .FormatDate article.CreatedOn }}</p>
Anything else????
Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to httprouter. If you need performance and good productivity, you will love Gin.
It features a Martini-like API with much better performance that is up to 40 times faster. Gin Gonic can be primarily classified as “Frameworks (Full Stack)” tools. SpartanGeek, Sezzle, and SEASON are some of the popular companies that use Gin Gonic.
TL;DR use SetHTMLTemplate
Looking at the Gin documentation, you can use your own templating engine.
By invoking r.SetHTMLTemplate(tmpl)
Gin itself is using the golang builtin html/template standard package.
You can use the same engine and add user defined functions.
Create the functions, using template.FuncMap:
funcMap := template.FuncMap{
"formatTime": func(raw int64) string {
t := time.Unix(raw, 0)
return t.Format("Jan 2 15:04:05 2006")
},
}
Instantiate a template:
tmpl := template.Must(template.New("main").Funcs(funcMap).ParseGlob("templates/**/*"))
Register the new template:
r := gin.Default()
r.SetHTMLTemplate(tmpl)
If you use same templates name for different endpoints, specify name:
{{ define "articles/list.tmpl"}}
<div class="list-group">
{{ range $article := .articles }}
<a href="/articles/{{ $article.Id }}" class="list-group-item">
<h4 class="list-group-item-heading">{{ $article.Title }}</h4>
<p class="list-group-item-text">{{ formatTime $article.CreatedOn }}</p>
<p class="list-group-item-text"></p>
</a>
{{ end }}
</div>
{{ end }}
formatTime: Is defined using template.FuncMap
To invoke, use the normal way:
c.HTML(http.StatusOK, "articles/list", gin.H{
"title": "Articles",
"articles": articles,
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With