go - 在 Go 中将未转义的 HTML 解析为 HTML 模板

标签 go go-html-template

我创建了这个非常简单的测试程序。

package main

import (
    "fmt"
    "github.com/microcosm-cc/bluemonday"
    "github.com/pressly/chi"
    "github.com/russross/blackfriday"
    "github.com/unrolled/render"
    "net/http"
)

func main() {
    r := chi.NewRouter()
    r.Get("/", homepageGET)
    http.ListenAndServe(":8080", r)
}

func homepageGET(w http.ResponseWriter, r *http.Request) {
    Renderer := render.New(render.Options{
        Directory:    "frontend",
        Extensions:   []string{".tmpl", ".html"},
        UnEscapeHTML: true,
    })
    unsafe := blackfriday.MarkdownCommon([]byte("**bolded text**"))
    markdownContent := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
    fmt.Print(string(markdownContent))
    Renderer.HTML(w, http.StatusOK, "index", map[string]interface{}{
        "content": fmt.Sprintf(string(markdownContent))})
}

然后我有一个 HTML 文件,除此之外什么都没有:

<body>
  {{ .content }}
</body>

fmt.Print 命令打印“<p><strong>bolded text</strong></p>”,而它作为“&lt;p&gt;&lt;strong&gt;bolded text&lt;/strong&gt;&lt;/p&gt;”插入到 HTML 页面中。

我相信它与转义的 HTML 有关,但对于展开/渲染包,我将其配置为未转义。我非常感谢任何帮助让测试程序正常工作(最好与展开/渲染一起)。

最佳答案

在 Go 中,您可以将已知的安全 html 字符串转换为 template.HTML类型,并且由于 unrolled/render使用 Go 的 html/template 来呈现 html 你应该可以使用它。

Renderer.HTML(w, http.StatusOK, "index", map[string]interface{}{
        "content": template.HTML(markdownContent),
})

关于go - 在 Go 中将未转义的 HTML 解析为 HTML 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43458824/

相关文章:

mysql - 无效的 DSN : network address not terminated (missing closing brace)

sorting - 如何按多个值对 go slice 进行排序?

Golang 模板 - 使用模板变量作为范围循环内的全局变量

go - 在 Go 中动态调用 template.ParseFiles() 而不是传入 x 个字符串的最佳方法是什么?

ssl - 使用自签名证书的 TLS 连接失败

mongodb - Mongo-go-driver error New client error ClientOptions in argument to mongo.NewClient 错误

提供静态文件时出现 golang 错误

go - 如何在Go中使用多个html模板(即具有基本模板或页脚模板)?

go - 如何在{{define“…”}}的gotemplate中为&lt;input&gt;和<label>标签创建唯一的ID?

基于加载模板的 css 类