3

I am trying to pass my Golang variables into a Javascript file. I have read multiple articles online, including How to pass variables and data from PHP to JavaScript?. I feel like I'm pretty close, but alas the most eloquent implementation to this problem eludes me.

I'm looking for a simple and elegant solution that injects an object value in Go with a variable in Javascript. I feel like this is a very common problem, so the lack of a clear tutorial on this surprises me.

My first file [server.go] servers an HTML page using the templating libraries in Golang passing in a context and serving them through Handlers.

type PassStruct struct{
    data    []int
    number1 int
    number2 int
}

//inject the structure into render
func render(w http.ResponseWriter, tmpl string, context Context){
       //parse context and fill in templating variables using template 
 } 

I now have an HTML document that is served, which adds a Javascript file to it.

 <html>
     <head>
     //import javascript file 
     </head>
     <body>
     //some body
     </body>
 </html>

Finally, the javascript file is what I am really interested in:

  var data; //some 
  var number1;
  var number2;

  function doSomething(){
  }

I need to send the PassStruct into the Javascript file, and map out each of the values within the structure to a variable in the Javascript file. I have tried AJAX calls, but have not had success so far.

2
  • For most templating languages JSON encoding is the safest way, see gobyexample.com/json Commented May 25, 2016 at 11:57
  • so did you find a solution to this problem? Commented Apr 1, 2020 at 19:39

3 Answers 3

3

Finally , after spending 2 days on the problem , i found an elegant way to work around it . We will use templates to solve this problem .

Read about templates usage in golang here - Understanding Templates with Examples .

Here is a sample code to pass a golang variable called golangVar in javascript .

HTML_File -

<html>
<head>
    <script>
        var golangVar = "{{.}}"
        console.log(golangVar);
    </script>
 </head>
 <body>
 <!--some body-->
 </body>
</html>

Golang HttpHandler -

Make sure you include "html/template" library in the golang code .

func golangHttpHandler(w http.ResponseWriter, r *http.Request) {
var golangVar string 
golangVar = "ProblemSolved" 
templ, err := template.ParseFiles("/home/PathToHTMLPage/HTML_File.html")
if(err!=nil){
    fmt.Println("Error = ",err)
}
err = templ.Execute(w, golangVar)
if(err!=nil){
    fmt.Println("Error = ",err)
}   
}

Also, a bonus tip - If you are working around with buffalo framework for golang , you can use default plush package for templating . Its similar to what we have done here with just a little bit of change in syntax and passing of html file . Read - Templating in Buffalo Framework

Sign up to request clarification or add additional context in comments.

1 Comment

That's how i got rid of the stupid javascript errors in my Code editor! Thank you!!
0

This way maybe helpful:

Html:

<html>
    <head>
     <!--import javascript file -->
        <script type="text/javascript" src="static/myjs.js"></script>
        <script type="text/javascript">
            myFunc({{.}});
        </script>
     </head>
     <body>
     <!--some body-->
     </body>
</html> 

Javascript:(myjs.js)

function myFunc(passStruct){
    var obj = Object();

    var data = passStruct.Data;
    var number1=passStruct.Number1;
    var number2=passStruct.Number2;

    obj.data=data;
    obj.number1=number1;
    obj.number2=number2;

    return obj;
 }

Comments

0

You can write your own template function and use it to marshal struct into json.

See my answer here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.