M
M
ML2017-02-26 23:36:59
go
ML, 2017-02-26 23:36:59

Why is there such a thing in the html template?

golang:

data, err := json.Marshal(Data)
log.Print(data);
//Вернет
//[{"ID":"1"}]

Template code:
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

1 answer(s)
A
Alexander Pavlyuk, 2017-02-27
@staffID

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()))
}

Or even prettier: https://play.golang.org/p/Ir4wLhHMuV
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()))
}

The reason is that since Go can't parse the js grammar completely, it's making sure it doesn't inadvertently allow code injection.
Go sees the brackets and understands that it needs to insert the contents of the js string literal, but because since it cannot fully guarantee that we will be inside the brackets, it secures itself and escapes the control characters so that in case of an error, js simply stops, but does not execute the inserted code.
Templates are only aimed at inserting data and should guarantee the programmer that this data will not be executed as code (unless, of course, you insert eval there yourself).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question