상세 컨텐츠

본문 제목

How to use 'Html/Template' For your Echo Server in Go!

Go

by 경밤 2020. 4. 18. 22:04

본문

반응형

Hi Everybody, In this post we are going to build a simple http server with template.

Prior to speaking, we have to know what does template doing.

Template is just a view engine. Have you ever used Node.JS? then you know there is a populur View Engine called 'ejs'. 

It's make with ejs. You can put values in 'static' html and, do some cool things in html.

Let's build it!

 

Ah, I'm sorry. I forgot to show you this directory struction.

Here it is. The developing environment that I set up is opened on GOPATH.

create bin, pkg, src, and make views folder on public folder. 

More go files will be created more step over.


1. Create main.go, HTTP Server

Frist, You must write template.go

It's the main point of this post. It will make your template usage more simple.

template.go

package main

import (
	"errors"
	"html/template"
	"io"

	"github.com/labstack/echo"
)

type Template struct { //the map[key] in key means 'Your html file name'
	templates map[string]*template.Template
}

func NewTemplate() *Template {
	return &Template{
		templates: make(map[string]*template.Template),
	}
}

//To be implemented the Template which has map[string] html templates.
// ** We don't use this function directly. The echo framework will use this.
func (t *Template) Render(w io.Writer, html_name string, data interface{}, c echo.Context) error {
	if tmpl, exist := t.templates[html_name]; exist { //Check existence of the t.templates[html_name]
		return tmpl.Execute(w, data) // ** It wll execute the map[string]interface{} data
	} else {
		return errors.New("There is no " + html_name + " in Template map.")
	}

}

//Set template on html_name so that the 'tmpl' will be okay in 'Render' function.
func (tmpl *Template) Add(html_name string, template *template.Template) {
	tmpl.templates[html_name] = template
}

It is very simple, but It's strong. You successfully reduced template code in main.go!

Next is handler.go

 

handler.go

package handler

import (
	"net/http"

	"github.com/labstack/echo"
)

func IndexHanlder(c echo.Context) error {
	//It looks like get rid of "index.html" and put it in :) 
	return c.Render(http.StatusOK, "index.html", map[string]interface{}{
		"name": "Mordern Artist",
		"greetings": "I'm very pleased to see you",
	})
}

In index.html, that will get 'name' to "mordern Artist".

Ah, Keep in mind the c.Render is not same with the 'Render' which we made.

 

main.go

package main

import (
	"html/template"

	"github.com/labstack/echo"
	"github.com/Your/Path/handler"
)

func main() {
	render_htmls := NewTemplate()
	render_htmls.Add("index.html", template.Must(template.ParseFiles("./public/views/index.html")))

	e := echo.New()
	e.Static("/", "public")
	e.Renderer = render_htmls

	e.GET("/", handler.IndexHanlder)
	e.Logger.Fatal(e.Start(":80"))
}

You make new Template that would be e.Renderer, Add the index.html, Set IndexHandler at e.GET event.

 

Finally, we just need to make html that get all datas from the handler passed.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>
</head>

<body>
    <h1>Name!</h1>
    <p>{{index . "name"}}</p>
    <h2>Welcome!</h2>
    <p>{{index . "greetings"}}</p>
</body>

</html>

Done. You could get the map to use ' . '(dot) then, what is the index?

index work/usage as follow:

1. Get Array(then, map[string]string)

2. {{ index .(value) indexing }} (then, index . key)

3. the code above, the map only string, string. so, we don't need detail value.

4. the final expression would be index . "key"

 

The result look very nice.

Thank you for reading!

반응형

관련글 더보기