Search code examples
javascriptgowebsocketgo-html-template

How to change templates using websockets?


I want to split the page into fragments and use the web sockets to change them without reloading the page.

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

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

I read the json from the client and find out which page to open.

func webSocketHandler(conn *websocket.Conn) {

 data := conn.ReadJSON(&msg)

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

  LoadVista(msg.Temp,conn)
}
var (
indexTemplate = template.Must(template.ParseFiles(indexVista,mainVista,headVista,footVista 
))
loginTemplate = 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)
 }

}

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;
}

But the "main" template does not change to the "page 2" template. Give advice on how to properly organize the change of templates using Go + js (webscokets). Thanks!


Solution

  • It was necessary to specify id.; <div id= "scene"> {{template "main"}} </div>

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

    Because What I'm looking for by Id and not by class. document.getElementById('scene').innerHTML = message