打印网页源代码的部分内容,类似于PHP中的操作,在Golang中如何实现?

huangapple go评论70阅读模式
英文:

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[&quot;title&quot;]
    p, err := loadPage(title)
    if err != nil {
        ...
    }
    // do other things

    template.ExecuteTemplate(w, &quot;results.html&quot;, M{
            &quot;title&quot;: title,
            &quot;results&quot;: results,
            &quot;pagination&quot;: true,
         }
    }

> results.html

{{range .Results }}
   &lt;h1&gt;{{ Result.Name }}&lt;/h1&gt;
   &lt;p&gt;{{ Result.Body }}&lt;/p&gt;
 {{ 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.

huangapple
  • 本文由 发表于 2014年8月20日 20:32:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/25404825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定