golang中的HTML模板 [英] HTML templates in golang

查看:162
本文介绍了golang中的HTML模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循以下教程:
golang tutorial - wiki 和我除了其他任务部分中的最后一点之外,我已经设法让所有工作都能正常工作。我的教程实施:

I'm following this tutorial: golang tutorial - wiki and I've managed to get everything working except the last point in the "other task" section. My Implementation of the tutorial:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "html/template"
    "regexp"
)

type Page struct {
    Title string
    Body []byte
}

func (p *Page) save() error {
    filename := "data/" + p.Title + ".txt"
    return ioutil.WriteFile(filename, p.Body, 0600)
}

func loadPage(title string) (*Page, error) {
    filename := "data/" + title + ".txt"
    body, err := ioutil.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return &Page{Title: title, Body: body}, nil
}

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    t, _ := template.ParseFiles("template/" + tmpl + ".html");
    t.Execute(w, p)
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/view/"):]
    p, err := loadPage(title)
    if err != nil {
        http.Redirect(w, r, "/edit/" + title, http.StatusFound);
        return
    }
    expr := regexp.MustCompile(`\[.+\]`)
    p.Body = expr.ReplaceAllFunc(p.Body, func ( match []byte) []byte {
        return []byte("<a href='/view/" + string(match) + "'>" + string(match) + "</a>")
    })
    renderTemplate(w, "view", p);
}

func saveHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/save/"):]
    body := r.FormValue("body")
    p := &Page{Title: title, Body: []byte(body)}
    p.save()
    http.Redirect(w, r, "/view/" + title, http.StatusFound)
}

func editHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/edit/"):]
    p, err := loadPage(title);

    if err != nil {
        p = &Page{Title: title}
    }
    renderTemplate(w, "edit", p);
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.Redirect(w, r, "/view/index", http.StatusFound)    
        })
    http.HandleFunc("/view/", viewHandler)
    http.HandleFunc("/edit/", editHandler)
    http.HandleFunc("/save/", saveHandler)
    http.ListenAndServe(":8080", nil)
    fmt.Println("Running");
}

html / template引擎按预期打印锚标签,但用html转义它实体。

html/template engine prints the anchor tag as expected, but escapes it with html entities. I've not been able to find appropriate way of doing it.

推荐答案

使用 template.HTML 来标记为安全的HTML。

Use template.HTML to mark the body as safe HTML.

以下函数将body to HTML。

The following function converts the body to HTML.

// Move to package-level variable so that it's compile once.
var linkPat = regexp.MustCompile(`\[.+\]`)

func toHTML(s string) template.HTML {

  // Escape everything in the string first to ensure that
  // special characters ('<' for example) are displayed as
  // characters and not treated as markup.
  s = template.HTMLEscapeString(s)

  // Insert the links.
  s = linkPat.ReplaceAllStringFunc(s, func(m string) string {
    s = s[1 : len(s)-1]
    return "<a href='/view/" + m + "'>" + m + "</a>"
  })

  return template.HTML(s)
}

使用以下方式呈现网页:

Render the page using:

renderTemplate(w, "edit", map[string]interface{}{
   "Title": p.Body,
   "Body": toHTML(p.Body),
})

这篇关于golang中的HTML模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆