Pass a variable from javascript to ejs

后端 未结 2 1092
夕颜
夕颜 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: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.

提交回复
热议问题