I'm using echo
framework. I'm stuck when trying to print URI :mynumber
as variable in template files.
All variable working fine except the URI :mynumber
. I have no idea how to include :mynumber
together with Name
& Age
Below is my server.go
:
package main
import (
"github.com/labstack/echo"
"html/template"
"io"
"net/http"
)
type Person struct {
Name, Age, Mynumber string
}
type (
Template struct {
templates *template.Template
}
)
func (t *Template) Render(w io.Writer, name string, data interface{}) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func main() {
e := echo.New()
p := Person{Name: "Mike San", Age: "35"}
t := &Template{
templates: template.Must(template.ParseFiles("public/views/testhere.html")),
}
e.Renderer(t)
e.Get("/testing/:mynumber", func(c *echo.Context) {
c.Render(http.StatusOK, "onlytestingtpl", p)
})
e.Run(":4444")
}
Below is public/views/testhere.html
:
{{define "onlytestingtpl"}}My name is {{.Name}}. I'm {{.Age}} years old. My number is {{.Mynumber}}.{{end}}
For your reference, below is example is print URI without template file:
package main
import (
"github.com/labstack/echo"
"net/http"
)
func main() {
e := echo.New()
e.Get("/users/:id", func(c *echo.Context) {
id := c.Param("id")
c.String(http.StatusOK, "My number is "+id)
})
e.Run(":4444")
}
You simply need to retrieve it from the URL as per your working sample:
number := c.Param("mynumber")
And set it on the Person
instance you're passing in:
p.Mynumber = number
Which would result in:
e.Get("/testing/:mynumber", func(c *echo.Context) {
number := c.Param("mynumber")
p.Mynumber = number
c.Render(http.StatusOK, "onlytestingtpl", p)
})