我正在尝试放置一个golang数组(也是切片、结构等)。转换为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>发布于 2018-03-14 20:37:03
通常你有一个包含模板文件的文件夹,所以首先你需要告诉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
https://stackoverflow.com/questions/49277604
复制相似问题