2016-07-01 9 views
4

Ich bin Neuling in Golang-Code sowie in Gin gonic. Ich habe ein Problem mit Gin gonic.Wie man golang code in html-datei schreibt (gin gonic framework)

In meinem Controller. Ich bekomme alle Artikel und rendern HTML-Datei nach Code.

c.HTML(http.StatusOK, "articles/list", gin.H{ 
    "title": "Articles", 
    "articles": articles, 
}) 

und Artikel haben Feld „CreatedOn“ Typ int64 (Erstellungsdatum) Also meiner Ansicht list.html, wie ich CreateOn Typ int64 zu Datumsformat analysieren kann.

<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> 

Dank all

ich eine Möglichkeit, dass ich eine Methode Format schreiben gefunden hatte()

func (a *Article) FormatDate(ab int64) string { 
    return "test Time" 
} 

in Modell "Artikel". dann aus meiner Sicht rufe ich

<p class="list-group-item-text">{{ .FormatDate article.CreatedOn }}</p> 

Alles andere ????

+0

Ist das nicht Ihr 'Format()' Ansatz zu arbeiten? – Nadh

+0

natürlich hat es funktioniert. Es ist eine Methode, ich möchte eine Hilfsfunktion für die Vorlage erstellen, aber ich weiß nicht, wie ich es aufrufen kann – Vutuz

Antwort

0

TL; DR Verwendung SetHTMLTemplate

am Gin Blickdocumentation, können Sie Ihren eigenen Template-Engine verwenden.

r.SetHTMLTemplate (tmpl)

Gin selbst wird mit Hilfe der golang builtin html/template Standardpaket Durch Aufruf.

Sie können dieselbe Engine verwenden und benutzerdefinierte Funktionen hinzufügen.

die Funktionen erstellen, template.FuncMap mit:

funcMap := template.FuncMap{ 
    "formatTime": func(raw int64) string { 
     t := time.Unix(raw, 0) 

     return t.Format("Jan 2 15:04:05 2006") 
    }, 
} 

eine Vorlage instanziiert:

tmpl := template.Must(template.New("main").Funcs(funcMap).ParseGlob("templates/**/*")) 

die neue Vorlage registrieren:

r := gin.Default() 
r.SetHTMLTemplate(tmpl) 

Wenn Sie für denselben Vorlagen-Namen verwenden verschiedene Endpunkte, geben Sie den Namen an:

{{ 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: definiert wird template.FuncMap

aufzurufen, verwenden Sie die normale Art und Weise:

c.HTML(http.StatusOK, "articles/list", gin.H{ 
    "title": "Articles", 
    "articles": articles, 
})