在 Go Fiber 应用程序中渲染模板

问题描述

有没有人有 gofiber 和模板的好例子?

我正在尝试通过 go fiber Html 模板显示视频列表

这是我的 Go 代码(实体):

type Video struct {
    Id          int    `json:"id"`
    Title       string `json:"title"`
    Description string `json:"description"`
    VideoUrl    string `json:"description"`
    Link        string `json:"description"`
}

var videos = []*Video{
    {
        Id:          1,Title:       "podcast #1",Description: "Here I discuss about stuff",VideoUrl:    "foo.m3u8",Link:        "videos/foo",},{
        Id:          2,Title:       "podcast #2",Description: "Still talking",VideoUrl:    "bar.m3u8",Link:        "videos/bar",}

这是我的 Go 代码(控制器):

func main() {
    // Fiber instance
    app := fiber.New(fiber.Config{
        Views: html.New("./views",".html"),})

    // Serve static assets
    app.Static("/","./public",fiber.Static{
        Compress: true,})

    // Routes
    app.Get("/",index)

    // Start server
    log.Fatal(app.Listen(":3000"))
}

// Handler
func index(c *fiber.Ctx) error {
    return c.Render("index",fiber.Map{
        "Videos": videos,})
}

这是我的伪 HTML :

<div class="col-lg-4">
    <video-js id={{.Id}} class="vjs-default-skin my-tuby-video" controls preload="auto" width="640" height="268">
    <source src="{{.VideoUrl}}" type="application/x-mpegURL">
    </video-js>
    <script>
    var player = videojs({{.Id}});
    </script>
    
    <h2>{{.Title}}</h2>
    <p>{{.Description}}</p>
    <p><a class="btn btn-secondary" href="#">{{.Link}}</a></p>
</div><!-- /.col-lg-4 -->

还有如何为列表中的每个视频重复这段 HTML 代码

预先感谢您的任何意见。

解决方法

正如 Cerise Limon 评论的那样:

{{range .Videos}}
<div class="col-lg-4">
    <video-js id={{.Id}} class="vjs-default-skin my-tuby-video" controls preload="auto" width="640" height="268">
    <source src="{{.VideoUrl}}" type="application/x-mpegURL">
    </video-js>
    <script>
    var player = videojs({{.Id}});
    </script>
    
    <h2>{{.Title}}</h2>
    <p>{{.Description}}</p>
    <p><a class="btn btn-secondary" href="#">{{.Link}}</a></p>
</div><!-- /.col-lg-4 -->
{{end}}

成功了。