使用template.HTML将正文标记为安全HTML。
以下函数将正文转换为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)}使用以下方式渲染页面:
renderTemplate(w, "edit", map[string]interface{}{ "Title": p.Body, "Body": toHTML(p.Body),})


