Home > front end >  Send variable from nodejs into js file that has rendered alongside html
Send variable from nodejs into js file that has rendered alongside html

Time:01-03

I'm pretty new to nodejs.

How do I pass a variable in my app.js, to the app.js file that renders together with my html? Is this possible?

For example, as below, trying to send the value of myvar to the /public/js/app.js file. I am aware that I could set it up as an inline script through the ejs file, just was looking for better alternatives to that.

app.js

app.use(express.static("public"));

//

app.get("/my-page", function (req, res) {

    var myvar = "Hello"
 
    res.render("my-page.ejs");
  }
});

//

/views/my-page.ejs

<h1>Hello World</h1>

<script type="text/javascript" src="./js/app.js"></script>
/public/js/app.js

var myvar2 = myvar   " World!"

console.log(myvar2)

Thanks!

CodePudding user response:

Since you are using Express as a framework you can use "Express.js res.locals Property".

app.js
    
app.use(express.static("public"));
    
app.get("/my-page", function (req, res) {
    
  var myvar = "Hello";

  res.locals.myvar = myvar; //You can set up the variable here

  res.render("my-page.ejs");
});

And then in the html you can access through:

/public/js/app.js

var myvar2 = window.myvar   " World!"; // You can access through window object

console.log(myvar2);

Then since you are using EJS template expression you can access it through:

<h1><%= myvar %></h1>

For more info you can look at express page

Some other way to access to the variable from HTML would be:

<script>
  var myVarContainer = document.getElementById("myvar");

  myVarContainer.innerHTML = '<%= myvar %>'; // Set the innerHTML with the variable value
</script>

But overall If its something more complex I would suggest you to use some library or framework (React or Angular) for data binding.

CodePudding user response:

JSON to the rescue. We send a <script> tag with the proper values. The trick is rendering the template file into html first, but express offers a callback for that.

// in node.js:

function my_render(res, template, data, obj) {
  
  res.render(template, data, (err, html) => {
    if (err) {
      throw "something"
    }
    html  = "<script>var my_var = "   JSON.stringify(obj)   ";</script>";
    res.send(html);
  });
});

// in client:
// my_var = object that was on server

  • Related