【问题标题】:Rendering templates in a Go Fiber application在 Go Fiber 应用程序中渲染模板
【发布时间】:2021-07-08 18:55:51
【问题描述】:

有没有人有 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?

提前感谢您的任何意见。

【问题讨论】:

  • 我添加了我在地图中放置视频的部分。我真的不确定下一步该做什么。
  • 使用{{range .Videos}} &lt;insert html shown in question &gt; {{end}} 覆盖视频。

标签: go templates render fibers


【解决方案1】:

正如 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}}

成功了。

【讨论】:

    猜你喜欢
    • 2012-10-29
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 2012-06-03
    • 2018-11-25
    相关资源
    最近更新 更多