简体   繁体   English

将参数传递给Node.js EJS模板

[英]Passing Params to nodejs ejs template

Guys i'm trying to render MongoDB record in my .ejs file, however, i console.log the variable prior the end of my route and i get the expected value, however, if becomes undefined in the .ejs file 伙计们,我正在尝试在.ejs文件中呈现MongoDB记录,但是,我在路由结束之前console.log该变量,但是我获得了预期的值,但是如果.ejs文件中的值未定义

below is the code: 下面是代码:

router.get("/new",function(req,res){
    var selectedMake;
    console.log("Welcome to new make route!");
    Make.find({},function(err,result){
        if(err){
            console.log("an error occured while fetching the data");
        }else{
            if(req.query.id){
                Make.findById(req.query.id,function(err,foundMake){
                    console.log("found the query string");
                    selectedMake = foundMake;
                    console.log(selectedMake); // renders expected value when passing valid ID in the query string
                })
            }
            res.render("vehicles/newvehiclemake",{selectedMake: selectedMake, makes:result,modelId: req.query.id});        
        }
    })

});

and here is the .ejs excerpt where the variable selectedMake is being used: 这是.ejs摘录,其中使用了selectedMake变量:

<% if (!typeof selectedMake == undefined) { %>
              <% selectedMake.models.forEach(function(model){ %>
                 <tr><td><%= model.name %></td></tr>
              <% }) %>
              <% }else { %>
              <tr><td>No Models available for the selected Make</td></tr>
              <% } %>

appreciate your input and thanks in advance. 感谢您的输入,并在此先感谢。

I'm not sure but you make mistake at first line in your .ejs file. 我不确定,但是您在.ejs文件的第一行犯了错误。 Try this: 尝试这个:

<% if (typeof selectedMake !== 'undefined') { %>

任何变量上的typeof返回一个字符串,因此您必须在ejs中检查'undefined'

<% if (typeof selectedMake !== 'undefined') { %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM