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

后端 未结 5 1307
情歌与酒
情歌与酒 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:06

    In app.js add line:

    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.use(express.static(__dirname + '/public')); // This line.
    

    In layout.ejs:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Authentication Example</title>
        <link rel="stylesheet" href="/stylesheets/style.css"/>
        <script src="/javascripts/jquery.js"></script>    
      </head>
      <body>
        <%- body %>
      </body>
    </html>
    

    In index.ejs or login.ejs:

    <h1>Login</h1>
    <form method="post" action="/login">
      <p>
        <label>Username:</label>
        <input type="text" name="username">
      </p>
      <p>
        <label>Password:</label>
        <input type="text" name="password">
      </p>
      <p>
        <input type="submit" value="Login">
      </p>
    </form>
    <script src="/javascripts/test.js"></script> <!-- Second Script -->
    

    In test.js:

    $(document).ready(function() {
        try{
            alert("Hi!!!");
        }catch(e)
        {
            alert("Error");
        }
    });
    

    Regards.

    0 讨论(0)
  • 2021-02-01 10:19

    As helpers and dynamicHelpers are gone in Express > 3, I rewrote pkyeck code so it works in Express 3.

    So in app.js have this instead of the helpers / dynamicHelpers. Leave everything else as is.

    app.locals({
        scripts: [],
      renderScriptsTags: function (all) {
        app.locals.scripts = [];
        if (all != undefined) {
          return all.map(function(script) {
            return '<script src="/javascripts/' + script + '"></script>';
          }).join('\n ');
        }
        else {
          return '';
        }
      },
      getScripts: function(req, res) {
        return scripts;
      }
    });
    
    0 讨论(0)
  • 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 "<script src='/js/" + script + "'></script>";
            }).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,

    0 讨论(0)
  • 2021-02-01 10:24

    found a solution here: Node.js with Express: Importing client-side javascript using script tags in Jade views?

    it's using jade instead of EJS but works all the same. here are some code-snippets for express 2.4.0.

    you have to add the following "helpers" to your app.js

    app.helpers({
      renderScriptsTags: function (all) {
        if (all != undefined) {
          return all.map(function(script) {
            return '<script src="/javascripts/' + script + '"></script>';
          }).join('\n ');
        }
        else {
          return '';
        }
      }
    });
    
    app.dynamicHelpers({
      scripts: function(req, res) {
        return ['jquery-1.5.1.min.js'];
      }
    });
    

    the layout.ejs looks sth like this:

    <!DOCTYPE html>
    <html>
      <head>
        <title><%= title %></title>
          <link rel='stylesheet' href='/stylesheets/style.css' />
          <%- renderScriptsTags(scripts) %>
      </head>
      <body>
        <%- body %>
      </body>
    </html>
    

    if you don't add any scripts to the scripts-array, only 'jquery-1.5.1.min.js' will be included - if you want to add files to a subpage you can do this like so:

    test.ejs

    <% scripts.push('jquery-ui-1.8.14.custom.min.js', 'jquery.validate.min.js') %>
    
    <h1><%= title %></h1>
    <p>I'm a template with 3 js files in the header</p>
    

    that's it.

    0 讨论(0)
  • 2021-02-01 10:25

    Thanks for illustrating this option pkyeck!

    In express 4.x app.locals is an object. Here's pkyeck's answer rewritten to work in express 4.x:

    app.locals.scripts = [];
    app.locals.addScripts=function (all) {
        app.locals.scripts = [];
        if (all != undefined) {
            return all.map(function(script) {
                return "<script src='/javascripts/" + script + "'></script>";
            }).join('\n ');
        }
        else {
            return '';
        }
    };
    app.locals.getScripts = function(req, res) {
        return scripts;
    };

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