Accessing passed EJS variable in Javascript file

前端 未结 5 869
轻奢々
轻奢々 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:50

    Three way to solve the problem...

    1. variant

      <script>
          var x = "<%= todos %>";
          console.log(x); 
      </script>
      
    2. variant

      <script>
          var x = "<%- todos %>";
          console.log(x); 
      </script>
      
    3. variant [XD]

      HTML:

      <p id="yy" style="display:none"><%= todos %></p>
      

      Javascript:

      <script>
          var x = document.getElementById("yy").innerText;
          console.log(x); 
      </script>
      
    0 讨论(0)
  • 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:

    <script>
     var x= <%- todos %>;
     console.log(x);
    </script>
    

    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.

    0 讨论(0)
  • 2020-12-05 13:03

    http://ejs.co/ says

    1. <% 'Scriptlet' tag, for control-flow, no output
    2. <%= Outputs the value into the template (HTML escaped)
    3. <%- Outputs the unescaped value into the template
    4. <%# Comment tag, no execution, no output

    Can you try using <%- in ejs to read variable value?

    0 讨论(0)
  • 2020-12-05 13:08

    By formatting the html printing of the JSON you get from the server and using javascript (my case jQuery) to retrieve that text, store it, and remove it from the html :)

    EJS:

    <span id='variableJSON' hidden>
        <%= JSON.stringify(passedInEjsVariable); %>
    </span>
    

    JavaScript:

    var variableJSON = JSON.parse($('#variableJSON').text());
    $('#variableJSON').remove();
    
    0 讨论(0)
  • 2020-12-05 13:12

    Only this works in my case. All versions with "" or with <%= fail.

    <script>
      var todos = <%-JSON.stringify(todos)%>;
      for (var item of todos) {
        console.log(item)
      }
    </script>
    

    Thing to note: if using VS Code with formatting on save for .ejs files, <%- gets split into <% - and you get Uncaught SyntaxError: Unexpected token ';' and what worked a second ago, suddenly stops working.

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