Pass a variable from javascript to ejs

后端 未结 2 1090
夕颜
夕颜 2020-12-11 16:16

I want to use a variable which is declared in javascript file to a ejs file.

javascript:

var express = require(\'express\');
var app = express();

va         


        
相关标签:
2条回答
  • 2020-12-11 16:52

    Here's a very simple example on how app.locals can be used to expose variables to (EJS) templates:

    // app.js
    var express = require('express');
    var app     = express();
    var server  = app.listen(3000);
    
    app.locals.myVar = 1;
    
    app.get('/', function(req, res) {
      res.render('index.ejs');
    });
    
    // views/index.ejs
    <% if (myVar) { %>
      <h1>myVar is here!</h1>
    <% } else { %>
      <h1>Boohiss no myVar!</h1>
    <% } %>
    
    0 讨论(0)
  • 2020-12-11 16:58

    The app.locals.myVar approach should work, so something must be getting in the way. But you could avoid using app.locals.myVar altogether and pass variables directly to your views with:

    var express = require('express');
    var app = express();
    
    app.get('/', function(req, res) {
        var myVar = 1;
        res.render('testPage', { myVar : myVar });
    });
    

    The myVar variable should now be available to the "testPage" ejs file. Inside of it you could do:

    <%= myVar %>
    

    And see it output "1".

    Lastly, make sure you have set the view engine to ejs:

    app.set('view engine', 'ejs');
    

    Otherwise it won't work.

    0 讨论(0)
提交回复
热议问题