is there a way to add CSS/JS later using EJS with nodejs/express

后端 未结 5 1320
情歌与酒
情歌与酒 2021-02-01 09:26

i\'m using the EJS template engine with nodejs/express and i\'m wondering if it\'s possible to add another css or js file in e.g the index.ejs (not the layout.ejs)

5条回答
  •  滥情空心
    2021-02-01 10:20

    Thanks @asprotte for providing this for express 4.x. Did you tested this? Because it does not appears to be working for me. So I have made some changes to your code here are they:

    Put this in app.js file

    app.locals.scripts = [];
    app.locals.addScripts=function (all) {
    app.locals.scripts = [];
        if (all != undefined) {
            app.locals.scripts =  all.map(function(script) {
                console.log(script);
                return "";
            }).join('\n ');
        }
    
    };
    app.locals.getScripts = function(req, res) {
        return app.locals.scripts;
    };
    

    then in template file put (I am using ejs template here) :

    <% addScripts(['cart.js']) %>
    

    Then in the layout file we need these to append at the bottom of the page get the scripts

    <%- getScripts() %>
    

    I have tested it and its working for me. Please correct me if I am wrong.

    Thanks,

提交回复
热议问题