将Params传递给nodejs ejs模板

时间:2016-08-07 20:13:47

标签: javascript node.js mongodb mongoose ejs

伙计们,我正在尝试在我的.ejs文件中呈现MongoDB记录,但是,我在路由结束之前调试变量并获取预期值,但是,如果在.ejs文件中未定义< / p>

下面是代码:

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});        
        }
    })

});

以下是使用变量selectedMake的.ejs摘录:

<% 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>
              <% } %>

感谢您的投入并提前感谢。

2 个答案:

答案 0 :(得分:0)

我不确定但你在.ejs文件的第一行犯了错误。 试试这个:

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

答案 1 :(得分:0)

任何变量的

package main import "fmt" func main() { const fm = "'%T'\t'%#[1]v'\t'%[1]v'\t%v\n" var i interface{} b, ok := i.(interface{}) fmt.Printf(fm, b, ok) // '<nil>' '<nil>' '<nil>' false i = 2 b, ok = i.(interface{}) fmt.Printf(fm, b, ok) // 'int' '2' '2' true i = "Hi" b, ok = i.(interface{}) fmt.Printf(fm, b, ok) // 'string' '"Hi"' 'Hi' true i = new(interface{}) b, ok = i.(interface{}) fmt.Printf(fm, b, ok) // '*interface {}' '(*interface {})(0xc042004330)' '0xc042004330' true i = struct{}{} b, ok = i.(interface{}) fmt.Printf(fm, b, ok) // 'struct {}' 'struct {}{}' '{}' true i = fmt.Println b, ok = i.(interface{}) fmt.Printf(fm, b, ok) // 'func(...interface {}) (int, error)' '(func(...interface {}) (int, error))(0x456740)' '0x456740' true i = Shape.Area b, ok = i.(interface{}) fmt.Printf(fm, b, ok) // 'func(main.Shape) float64' '(func(main.Shape) float64)(0x401910)' '0x401910' true } type Shape interface { Area() float64 } 都会返回一个字符串,因此您必须在ejs中检查typeof

'undefined'