Golang if else in HTML templates tutorial #7

Golang if else in HTML templates tutorial #7


main.go Source Code file

<div>package main</div>
<div>import (</div>
<div>    "html/template"</div>
<div>    "net/http"</div>
<div>func main() {</div>
<div>    type Student struct {</div>
<div>        Name     string</div>
<div>        Class    int</div>
<div>        Reg      int</div>
<div>        Promoted bool</div>
<div>    }</div>
<div>    data := Student{</div>
<div>        Name:     "khan",</div>
<div>        Class:    12,</div>
<div>        Reg:      232,</div>
<div>        Promoted: false,</div>
<div>    }</div>
<div>    tmpl, _ := template.ParseGlob("templates/*.html")</div>
<div>    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {</div>
<div>        tmpl.ExecuteTemplate(w, "index.html", data)</div>
<div>    })</div>
<div>    http.ListenAndServe(":8080", nil)</div>

HTML TEMPLATE Source Code file

<div>&lt;html lang="en"&gt;</div>
<div>    &lt;meta charset="UTF-8"&gt;</div>
<div>    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;</div>
<div>    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;</div>
<div>    &lt;title&gt;GOLANG INDEX HTML&lt;/title&gt;</div>
<div>    &lt;h1&gt;Student Result and Promotion&lt;/h1&gt;</div>
<div>    {{if .Promoted}}</div>
<div>        congrats {{.Name}} from {{.Class}} and {{.Reg}}</div>
<div>    {{else}}</div>
<div>        failed {{.Name}} from {{.Class}} and {{.Reg}}</div>
<div>    {{end}}</div>



Tony BB

TonyBB is a Coach , marketer, hypnotist and a founder of RSKVF Production who specializes in providing simple, affordable, and easy to use solutions for Life.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: