Skip to content
Advertisement

Passing variable from app.js to ejs file into a script tag

I’m trying to pass variable which is defined in app.js into a script tag inside and ejs file. So the app.js in short looks like this:

//app.js
var express = require("express")
var app = express()
var request = require("request")



var thelist =[]
app.locals.myVar = thelist.length;

app.get("/", function(req, res){
    res.render("search")
})

app.get("/show/:id", function (req, res) {
    var id = req.params.id;
    thelist.push(id)
    console.log(thelist);
    res.redirect('/')
});

The variable I want to pass is the app.locals.myVar, acutally this method doesnt work and I still get that myVar is not defined in ejs file

The ejs file is here:

//search.ejs
<html>
    <head>
        <title>MYMDB</title>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.css">
        <link rel="stylesheet" type="text/css" href="/stylesheets/app.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>

    </head>
    <body>


    <a id="show-data" href="/data" class="ui right floated disabled button"> 
      See the table 
    </a>



  <script>
    $('#run').click(function() {
      $('#show-data').removeClass('ui disabled button');
      $('#show-data').addClass('ui loading button');
      setTimeout(function () {      
          $('#show-data').removeClass("ui loading button");
          $('#show-data').addClass('ui basic button')
              }, myVar*2000);
   });
  </script>

  </body>
</html>

As you can see im trying to use myVar- the variable that is obtained on the server side js and then using it in the client side js. But it appears to not be recognized in the ejs file.

Advertisement

Answer

res.render() is parameterized. So, try:

res.render("search", {
    myVar: "value"
});

See Express docs for: app.render() and res.render().

Your HTML should look something like this with the <%= myVar %> included.

<html>
<body>
    <h1>Hello</h1>
    <p>Lorem</p>
    <script>
        // Print out the variable I got
        console.log(<%= myVar %>)
        // or
        console.log("<%= myVar %>")
    </script>
</body>
</html>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement