Answer the question
In order to leave comments, you need to log in
Why is there such a thing in the html template?
golang:
data, err := json.Marshal(Data)
log.Print(data);
//Вернет
//[{"ID":"1"}]
var data = JSON.parse( "{{.Data.data}}" );
//Результат
//var data = JSON.parse( "[{\x22ID\x22:\x221\x22}]" );
Answer the question
In order to leave comments, you need to log in
This is a valid javscript entry for the string [{"ID":"1"}]
But you can make it prettier: https://play.golang.org/p/brmFG2PGJD
package main
import (
"bytes"
"fmt"
"html/template"
"log"
)
func main() {
out := bytes.NewBuffer([]byte{})
t, err := template.New("foo").Parse(`<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
var data = JSON.parse( {{.}} );
</script>
</head>
<body>
</body>
</html>`)
if err != nil {
log.Fatal("Cannot parse the template: ", err)
}
err = t.Execute(out, `[{"ID":"1"}]`)
if err != nil {
log.Fatal("Cannot execute the template: ", err)
}
fmt.Println(string(out.Bytes()))
}
package main
import (
"bytes"
"fmt"
"html/template"
"log"
)
type A []struct {
ID string
}
func main() {
out := bytes.NewBuffer([]byte{})
t, err := template.New("foo").Parse(`<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
var data = {{.}};
</script>
</head>
<body>
</body>
</html>`)
if err != nil {
log.Fatal("Cannot parse the template: ", err)
}
data := A{
{ID: "1"},
}
err = t.Execute(out, data)
if err != nil {
log.Fatal("Cannot execute the template: ", err)
}
fmt.Println(string(out.Bytes()))
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question