duancong7573 2014-08-20 12:32
浏览 44
已采纳

使用PHP在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条回答 默认 最新

  • douzhui1972 2014-08-20 12:37
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持