duanji8887 2013-09-03 10:31
浏览 139
已采纳

html / template:如何在没有<script>标记的情况下转义JavaScript(JSON)?

The following program writes

<html><body>Hello <script>[{"A":"foo","B":"bar"},{"A":"bar","B":"baz"}]</script></body></html>

because of the <script>-Tag (which does some JavaScript JSON to string encoding). How can I get the same without the <script>-Tag?. That is: I'd like to write

t, err := template.New("foo").Parse("<html><body>Hello <pre>{{.}}</pre></body></html>
")

and get

<html><body>Hello <pre>[{"A":"foo","B":"bar"},{"A":"bar","B":"baz"}]</pre></body></html>

back? I have seen the | ... syntax for contexts in the templates package, but which context should I use?

package main

import (
    "html/template"
    "log"
    "os"
)

func main() {

    type keyvalue struct {
        A, B string
    }

    a := []keyvalue{{"foo", "bar"}, {"bar", "baz"}}

    t, err := template.New("foo").Parse("<html><body>Hello <script>{{.}}</script></body></html>
")
    if err != nil {
        log.Fatal(err)
    }
    err = t.ExecuteTemplate(os.Stdout, "foo", a)
    if err != nil {
        log.Fatal(err)
    }
}

Background: I need to generate an HTML attribute for the X-Editable JavaScript library, which looks like this: source="[{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...]"

  • 写回答

3条回答 默认 最新

  • dongtangxi1584 2013-09-03 10:59
    关注

    If you have "special needs" regarding the generated HTML you might use text/template.

    But maybe in your case it would be better to just convert a to a string representation first and stuff this string into the rendering. I think this makes it much clearer what you are trying to do.

    Or: Write your own filter function (see http://golang.org/pkg/html/template/#Template.Funcs) which does this string processing an call your function in the template.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?