英文:
Print parts of a web-page's source in Golang like PHP
问题
我正在尝试使用Go语言生成一个网页。我目前正在使用Goji框架(http://goji.io),我希望生成网页的所有头部和部分内容,但是我希望其中一些内容是根据代码的结果来编写的。
例如,在PHP中,可以编写HTML、js或CSS,然后在PHP标签中编写在那里解释的代码。
我该如何编写我的HTML、CSS和JS,并在其中包含Golang代码,以便在渲染页面时进行编译和执行?
英文:
I'm trying to generate a web page in Go lang. I'm currently using the Goji framework ( http://goji.io ) and I want to generate all of the heads and parts of the body of the web-page, but then I want some of the content to be written based on results from the code.
For example as in PHP, one can write HTML, js, or CSS and then in the PHP tags, write the code which is interpreted there.
How can I write my html, css, and js and then have Golang code within it that is complied and executed as the page is rendered?
答案1
得分: 3
如问题13中所提到的,使用Go的html/template包。
即:
// 简写
type M map[string]interface{}
func viewHandler(c web.C, w http.ResponseWriter, r *http.Request) {
title := c.URLParams["title"]
p, err := loadPage(title)
if err != nil {
...
}
// 做其他事情
template.ExecuteTemplate(w, "results.html", M{
"title": title,
"results": results,
"pagination": true,
}
}
> results.html
{{range .Results }}
<h1>{{ .Name }}</h1>
<p>{{ .Body }}</p>
{{ end }}
在zenazn/goji/example/main.go
中也推荐使用模板。
elithrar在评论中还提到了“编写Web应用程序”文章中的“html/template包”部分。
英文:
As mentioned in issue 13, use Go html/template package.
i.e.
// Shorthand
type M map[string]interface{}
func viewHandler(c web.C, w http.ResponseWriter, r *http.Request) {
title := c.URLParams["title"]
p, err := loadPage(title)
if err != nil {
...
}
// do other things
template.ExecuteTemplate(w, "results.html", M{
"title": title,
"results": results,
"pagination": true,
}
}
> results.html
{{range .Results }}
<h1>{{ Result.Name }}</h1>
<p>{{ Result.Body }}</p>
{{ end }}
Using a template is also recommended in zenazn/goji/example/main.go
.
elithrar also references in the comments the "Writing Web Applications article, section The html/template package" for more.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论