gpt4 book ai didi

go - 在 Golang 中像 PHP 一样打印网页源代码的一部分

转载 作者:IT王子 更新时间:2023-10-29 01:59:53 32 4
gpt4 key购买 nike

我正在尝试使用 Go 语言生成网页。我目前正在使用 Goji 框架 ( http://goji.io ),我想生成网页的所有头部和主体部分,但是我希望根据代码的结果编写一些内容.

例如在 PHP 中,可以编写 HTML、js 或 CSS,然后在 PHP 标记中编写在那里解释的代码。

我如何编写我的 html、css 和 js,然后在其中包含在呈现页面时编译和执行的 Golang 代码?

最佳答案

issue 13 中所述, 使用 Go html/template包。

// 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 }}

zenazn/goji/example/main.go 中也推荐使用模板.

elithrar还引用了 in the comments "Writing Web Applications article, section The html/template package "更多信息。

关于go - 在 Golang 中像 PHP 一样打印网页源代码的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25404825/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com