Accessing EJS variable in Javascript logic

后端 未结 6 488
不知归路
不知归路 2020-12-02 20:21

I\'m working on a Node.js app (it\'s a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the pr

6条回答
  •  臣服心动
    2020-12-02 21:04

    In the EJS template:
    ex:- testing.ejs

    
    
    
    
    

    In the Server side script:
    ex: Router.js

    res.render('/testing', {
        data: data // any data to be passed to ejs template
    });
    

    In the linked js (or jquery) script file:
    ex:- script.js In JavaScript:

    console.log(parsed_data)
    

    In JQuery:

    $(document).ready(function(){
        console.log(parsed_data)
     });
    

    Note: 1. user - instead of = in <% %> tag
    2. you can't declare or use data passed from router to view directly into the linked javascript or jquery script file directly.
    3. declare the <% %> in the EJS template only and use it any linked script file.

    I'm not sure but I've found it to be the best practice to use passed data from router to view in a script file or script tag.

提交回复
热议问题