我正在使用echo框架。我在尝试将 URI 打印:mynumber为模板文件中的变量时卡住了。除了 URI 之外的所有变量都可以正常工作:mynumber。我不知道如何:mynumber与Name&一起包含Age以下是我的server.go:package mainimport ( "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")}以下是public/views/testhere.html:{{define "onlytestingtpl"}}My name is {{.Name}}. I'm {{.Age}} years old. My number is {{.Mynumber}}.{{end}}供您参考,以下是不带模板文件的打印 URI 示例:package mainimport ( "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")}
1 回答
慕桂英4014372
TA贡献1871条经验 获得超13个赞
您只需要根据您的工作示例从 URL 中检索它:
number := c.Param("mynumber")
并将其设置在Person您传入的实例上:
p.Mynumber = number
这将导致:
e.Get("/testing/:mynumber", func(c *echo.Context) {
number := c.Param("mynumber")
p.Mynumber = number
c.Render(http.StatusOK, "onlytestingtpl", p)
})
- 1 回答
- 0 关注
- 185 浏览
添加回答
举报
0/150
提交
取消