Accessing passed EJS variable in Javascript file

前端 未结 5 897
轻奢々
轻奢々 2020-12-05 12:05

RESTful routes js file:

// index route - show all todos
router.get(\"/\", middleware.isLoggedIn,function(req,res) {
  Todo.find({ \"author.id\" : req.user._i         


        
5条回答
  •  盖世英雄少女心
    2020-12-05 12:57

    I am afraid you can't use EJS tags inside a file with a .js extension.

    If you put the js code at the bottom of the EJS document, there is no problem.

    In the backend you do:

    res.render('todo/index', {todos: JSON.stringify(alltodos)}); 
    

    In your ejs file you do:

    
    

    This works fine. I ve just tested for my project.

    If you want to use the same code inside a separate file with .js extension, it will not work. You get an 'unexpected token <' error in the browser console.

    The only option you have is to print todos into a hidden DIV inside the ejs file and then get in through javascript (you can use innerText or innerHTML) and store it inside a variable. A bit hacky but it does the trick.

提交回复
热议问题