N
N
Nube2018-03-17 09:46:53
JavaScript
Nube, 2018-03-17 09:46:53

Why don't Go + js templates change?

I want to change the "main" template to "page2" .

{{define "index"}}
{{template "head"}}

    <div class = "scene">
         {{template "main"}}
    </div>

{{template "foot"}}
{{end}}

For this I am reading json from the client
func WebSocketConnect(w http.ResponseWriter,r *http.Request)  {
  conn,err := upGrader.Upgrade(w, r, nil)
  defer conn.Close()
  if err != nil {
    log.Println(err)
    return
  }


  webSocketHandler(conn)

}
func webSocketHandler(conn *websocket.Conn) {

  data := conn.ReadJSON(&msg)

  if data != nil {
    log.Fatal(data)
    return
  }

  LoadVista(msg.Temp,conn)

}

Then I prepare the template and send it to the socket
var (
  indexTemplate = template.Must(template.ParseFiles(indexVista,mainVista,headVista,footVista))
  page2Template = template.Must(template.ParseFiles(loginVista))
)
/****************************************************************************/


func LoadVista(nameTemplate string, conn *websocket.Conn) {
  switch nameTemplate {
  case "page2":
    templateWsRender(nameTemplate,conn)
  }

}
func templateWsRender(name string,conn *websocket.Conn){
  //defer conn.Close()
  var buf  bytes.Buffer
  data := page2Template.ExecuteTemplate(&buf,name,nil)
  if data!=nil{
    log.Fatal(data)
  }
  err := conn.WriteMessage(1,buf.Bytes())
  if err!=nil{
    log.Fatal(err)
  }

}

this is the client code
var socket = new WebSocket('ws://localhost:7030/ws' )

socket.onmessage = function (event) {
    var message = event.data
    loadVista(message)
}

elem.addEventListener( "click" , sendQuery);
function sendQuery() {
    var page = {
        query_type :"openLink",
        temp: "page"
    }
    var event = JSON.stringify(page);

    socket.send(event);
}

function loadVista(message) {
    //alert(message)
    document.getElementById("scene").innerHTML = message.data;
}

if you use alert, you can see that the code from another template comes, but for some reason it does not change.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Decadal, 2018-03-17
@Nube

if you can see by //alert(message) that the code is coming from another template, then message.data; - incorrect expression.

var a = {'data':1}; 
alert(a); //[object] 
// если бы там был валидный объект, вы бы не увидели содержимого через alert

Make sure you put message.data in innerHtml and not message.
Maybe you need it like this -
or
message = JSON.parse(message);
document.getElementById("scene").innerHTML = message.data;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question