javascript - Passing variable from app.js to ejs file into a script tag - Stack Overflow

I'm trying to pass variable which is defined in app.js into a script tag inside and ejs file.So t

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=".2.13/semantic.css">
        <link rel="stylesheet" type="text/css" href="/stylesheets/app.css">
        <script src=".1.1/jquery.min.js"></script>
        <script src=".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.

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./ajax/libs/semantic-ui/2.2.13/semantic.css">
        <link rel="stylesheet" type="text/css" href="/stylesheets/app.css">
        <script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare./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.

Share Improve this question asked Nov 6, 2017 at 20:29 Alex TAlex T 3,87615 gold badges70 silver badges126 bronze badges 1
  • res.render() is parameterized. So, try res.render("search", {some:"var"}); – zero298 Commented Nov 6, 2017 at 20:31
Add a ment  | 

3 Answers 3

Reset to default 4

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>

So the general way of doing this is when you render a template pass in a data/object structure with all the data your template needs as follows:

//
// Pass all your objects, globals as references in your server side 
// code/endpoint, below i have also passed a library moment js so i
// can use that server side in my template for dates
// 
var data = {name: "Hello World", age:32, local: app.local, moment:moment}

Then when you render your template pass in the data structure

res.render("template", data);

In your template

<h1><%=name=></h1>
<h2><%=age%>
<script>
  var scope = <%=data.local%>
</script>

Or even better pass it as an element attribute (safer as it's passed as a string and decoded using JSON.parse.

<body id="body" data-server-scope="<%=data.local%>">

<Script>var scope = JSON.parse(document.getElementById("body").attr("data-server-scope"));</script>

Either solution will pass the server data (scope) down to your js client, ihave passed data.local, you could call this data.client or you could just pass down all the data structure, but in my example i have a reference to moment which can only be used within the template, it can't be passed down magically to the client, in-case you are wondering.

Whatever you pass data from controller to template ejs and want to use them inside script , There is two different things happen if send data is string then you normally do ,

res.render("template", {data: {name: 'name',permission: {id: 1, name: 'test'}} );

<script>
  var scope = "<%=name%>"
</script>

If you send object data then you must use string literals ,

``

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745109425a4611757.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信