html - 如何在 golang gin web 框架中使用 golang 数据呈现 HTML?

标签 html go go-gin

我正在尝试将一个 golang 数组(还有 slice、struct 等)放置到 HTML 中,这样当从 golang gin web 框架返回 HTML 时,我可以在 HTML 元素内容中使用数组元素。另一个问题是如何循环渲染这些数据?比如 Flask jinja 以这种方式工作。

{% block body %}
  <ul>
  {% for user in users %}
  <li><a href="{{ user.url }}">{{ user.username }}</a></li>
  {% endfor %}
  </ul>

最佳答案

通常你有一个包含模板文件的文件夹,所以首先你需要告诉 gin 这些模板所在的位置:

router := gin.Default()
router.LoadHTMLGlob("templates/*")

然后在处理程序函数中,您只需将模板名称数据传递给 HTML 函数,如下所示:

func (s *Server) renderIndex(c *gin.Context) {
    c.HTML(http.StatusOK, "index.tmpl", []string{"a", "b", "c"})
}

index.tmpl 中,您可以像这样循环数据:

{{range .}}
    {{.}}
{{end}}

. 始终是当前上下文,因此第一行 . 是输入数据,范围循环内 . 是当前元素.

模板示例:https://play.golang.org/p/4_IPwD3Y84D

关于模板的文档:https://golang.org/pkg/text/template/

很好的例子:https://astaxie.gitbooks.io/build-web-application-with-golang/en/07.4.html

关于html - 如何在 golang gin web 框架中使用 golang 数据呈现 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277604/

相关文章:

json - 使用Golang从AWS api解析数据

go - 来自 PostForm 的 Gin Gonic 值数组

reactjs - 为什么使用 react-admin 为 API 端点获取 404?

javascript - 使用 javascript 或 jQuery 匹配循环中项目的宽度

html - 如何阻止背景模糊的视差 div?

go - gcloud 应用程序部署说 : exec: "git": executable file not found in $PATH

cookies - go-gin 无法设置 cookie

javascript - 简单的 HTML 页面出现 JS 错误 - "SyntaxError: missing ; before statement"和 "ReferenceError: calculateAdvantage is not defined"

html - CSS 代码不适用于 chrome 和 Firefox,但适用于 IE

go - 如何使用 golang 写入已打开的 .xlsx 文件