7

我正在尝试呈现已经在字符串上的 HTML,而不是在 Gin 框架上呈现模板。

c.HTML函数上的GET("/")函数需要渲染一个模板。

但是POST("/markdown")我已经在一个字符串上渲染了那个 HTML。

我怎样才能在杜松子酒上退货?

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/russross/blackfriday"
    "log"
    "net/http"
    "os"
)

func main() {

    router := gin.New()
    router.Use(gin.Logger())
    router.LoadHTMLGlob("templates/*.tmpl.html")

    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl.html", nil)
    })

    router.POST("/markdown", func(c *gin.Context) {
        body := c.PostForm("body")
        log.Println(body)
        markdown := blackfriday.MarkdownCommon([]byte(c.PostForm("body")))
        log.Println(markdown)
        // TODO: render markdown content on return
    })

    router.Run(":5000")
}
4

3 回答 3

11

您可以将处理后的降价字节数组返回为 aRAW Data并将内容类型设置为text/html; charset=utf-8

这就是它的样子

router.POST("/markdown", func(c *gin.Context) {
        body, ok := c.GetPostForm("body")
        if !ok {
            c.JSON(http.StatusBadRequest, "badrequest")
            return
        }
        markdown := blackfriday.MarkdownCommon([]byte(body))
        c.Data(http.StatusOK, "text/html; charset=utf-8", markdown)
    })
于 2017-01-05T12:07:52.760 回答
2

您还可以对内容类型使用常量:

const (
    ContentTypeBinary = "application/octet-stream"
    ContentTypeForm   = "application/x-www-form-urlencoded"
    ContentTypeJSON   = "application/json"
    ContentTypeHTML   = "text/html; charset=utf-8"
    ContentTypeText   = "text/plain; charset=utf-8"
)
c.Data(http.StatusOK, ContentTypeHTML, []byte("<html></html>"))
于 2021-04-23T19:51:39.757 回答
0

将输出转换blackfriday.MarkdownCommon()template.HTMLlike:

markdown := blackfriday.MarkdownCommon([]byte(c.PostForm("body")))
c.HTML(http.StatusOK, "markdown.html", gin.H {
    "markdown": template.HTML(markdown),
})
于 2021-11-23T08:25:38.177 回答