Golang Martini模板在渲染Markdown时只显示HTML。

huangapple go评论100阅读模式
英文:

Golang Martini Templates Just Showing HTML when Rendering Markdown

问题

我正在使用Golang、Martini、Martini-Contrib Renderer包和Blackfriday编写一个简单的博客。

我能够将帖子存入数据库并从数据库中取出,没有任何问题。我甚至能够将帖子的正文作为HTML从数据库中取出并放入我的结构体中,但是当我们渲染模板时,输出只是普通的文本HTML,而不是应该显示的漂亮样式。

代码托管在这里:

http://bitbucket.org/ChasingLogic/goblog

任何帮助都将不胜感激。

编辑:

你可以在这里看到它的效果:

http://chasinglogic.com/

英文:

I am working on writing a simple blog in Golang using Martini, the Martini-Contrib Renderer package, and Blackfriday.

I am able to get the post into the DB and out of the DB with no issues. I even get the Body of the post out of the DB and into my struct as html however when we render the template the output is just plain text html and not looking pretty like it should.

Code is hosted here:

http://bitbucket.org/ChasingLogic/goblog

Any help would be great.

EDIT:

You can see what it's doing here:

http://chasinglogic.com/

答案1

得分: 2

Golang模板默认会对变量进行转义。当变量包含HTML且来源可信时,可以使用template.HTML代替string

http://golang.org/pkg/html/template/#HTML

> type HTML string
>
> HTML封装了一个已知安全的HTML文档片段。它不应该用于来自第三方的HTML,也不应该用于包含未闭合标签或注释的HTML。经过可靠的HTML清理器处理的输出和通过此包转义的模板可用于HTML。

我会通过以下方式进行修复:

type Post struct {
  Title  string
  Body   string
  Author string
  Date   string
}

改为

type Post struct {
  Title  string
  Body   template.HTML
  Author string
  Date   string
}

然后将

post.Body = string(blackfriday.MarkdownCommon([]byte(preFormatMarkdown)))

改为

post.Body = template.HTML(blackfriday.MarkdownCommon([]byte(preFormatMarkdown)))
英文:

Golang templates escape variables by default. You can use template.HTML instead of string when it contains HTML and the source is trusted (which, in this instance, it seems to be).

http://golang.org/pkg/html/template/#HTML

> type HTML string
>
> HTML encapsulates a known safe HTML document fragment. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments. The outputs of a sound HTML sanitizer and a template escaped by this package are fine for use with HTML.

The way I would fix it would be by changing this

type Post struct {
  Title  string
  Body   string
  Author string
  Date   string
}

to

type Post struct {
  Title  string
  Body   template.HTML
  Author string
  Date   string
}

And then change

post.Body = string(blackfriday.MarkdownCommon([]byte(preFormatMarkdown)))

to

post.Body = template.HTML(blackfriday.MarkdownCommon([]byte(preFormatMarkdown)))

huangapple
  • 本文由 发表于 2014年11月4日 10:47:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/26726930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定