templates - Go:在模板文件中打印 URI(echo 框架)

标签 templates go

我正在使用 echo 框架。尝试将 URI :mynumber 打印为模板文件中的变量时,我卡住了。

除了 URI :mynumber 之外的所有变量都工作正常。我不知道如何将 :mynumberName & Age

一起包括在内

下面是我的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")
}

下面是public/views/testhere.html:

{{define "onlytestingtpl"}}My name is {{.Name}}. I'm {{.Age}} years old. My number is {{.Mynumber}}.{{end}}

供您引用,下面是没有模板文件的打印 URI 示例:

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")
}

最佳答案

您只需根据您的工作示例从 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)
})

关于templates - Go:在模板文件中打印 URI(echo 框架),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958132/

相关文章:

c++日志函数使用模板SFINAE进行条件编译

c++ - std::max 函数 VS '>' 运算符中 int 和 long long int 之间的最大值

Node.js Express 3.x 将变量传递给 View

c++ - std::is_assignable 和 const 指针对象

php - 服务器端程序员的好模板,但在 CSS 和设计方面很糟糕?

go - 最大化 CustomResourceDefinition 可以拥有的 CustomResource 数量 | kubebuilder 和运营商 SDK

Go 构建失败, fatal error : rocksdb/c. h

xml - Go Parse XML to struct by tag 属性

go - Println 改变 slice 的容量

go - 相当于 golang 中的 gpg --sign 吗?