使用go-html-transform预处理HTML:替换失败

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

Using go-html-transform to preprocess HTML: Replace fails

问题

这个关于白名单HTML标签的问题开始,我一直在尝试Jeremy Wall的go-html-transform。为了改进可搜索的文档,我在这里提问,而不是直接打扰作者...希望这对于SO来说不是太具体的工具。

App Engine,最新的SDK。Post.Body是一个[]byte。这个是有效的:

package posts

import (
    // ...      
    "html/template"
    "code.google.com/p/go-html-transform/html/transform"
    "code.google.com/p/go-html-transform/h5"
)

// ...

// 预处理帖子正文,然后将其作为HTML()返回给模板,以避免html/template的转义可允许的标签
func (p *Post) BodyHTML() template.HTML {
    doc, _ := transform.NewDoc(string(p.Body))
    t := transform.NewTransform(doc)

    // 在任何<strong></strong>节点的末尾添加一些文本。
    t.Apply(transform.AppendChildren(h5.Text("<em>Foo</em>")), "strong")
    return template.HTML(t.String())
}

结果:

<strong>Blarg.<em>Foo</em></strong>

然而,如果我使用类似以下的代码而不是AppendChildren():

t.Apply(transform.Replace(h5.Text("<em>Foo</em>")), "strong")

我会得到一个内部服务器错误。我是否误解了Replace()的用法?现有的文档表明这种操作应该是可能的。

英文:

Following on from this question on whitelisting HTML tags, I've been experimenting with Jeremy Wall's go-html-transform. In the hopes of improving searchable documentation I'm asking this here rather than pestering the author directly... hopefully this isn't too tool-specific for SO.

App Engine, latest SDK. Post.Body is a []byte. This works:

package posts

import (
    // ...      
    &quot;html/template&quot;
    &quot;code.google.com/p/go-html-transform/html/transform&quot;
    &quot;code.google.com/p/go-html-transform/h5&quot;
)

// ...

// Pre-process post body, then return it to the template as HTML()
// to avoid html/template&#39;s escaping allowable tags
func (p *Post) BodyHTML() template.HTML {
    doc, _ := transform.NewDoc(string(p.Body))
    t := transform.NewTransform(doc)

    // Add some text to the end of any &lt;strong&gt;&lt;/strong&gt; nodes.
    t.Apply(transform.AppendChildren(h5.Text(&quot;&lt;em&gt;Foo&lt;/em&gt;&quot;)), &quot;strong&quot;)
    return template.HTML(t.String())
}

Result:

&lt;strong&gt;Blarg.&lt;em&gt;Foo&lt;/em&gt;&lt;/strong&gt;

However, if instead of AppendChildren() I use something like the following:

t.Apply(transform.Replace(h5.Text(&quot;&lt;em&gt;Foo&lt;/em&gt;&quot;)), &quot;strong&quot;)

I get an internal server error. Have I misunderstood the use of Replace()? The existing documentation suggests this sort of thing should be possible.

答案1

得分: 2

在App Engine之外运行您的转换代码时,它会发生恐慌,并且您可以在源代码中看到该点的TODO。然后,阅读代码并看到如果给定根节点,它将会发生恐慌并不太困难。

英文:

Running your transform code outside of App Engine, it panics and you can see a TODO in the source at that point. Then it's not too much harder to read the code and see that it's going to panic if given a root node.

huangapple
  • 本文由 发表于 2012年4月9日 11:22:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/10068552.html
匿名

发表评论

匿名网友

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

确定