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

后端 未结 5 1316
情歌与酒
情歌与酒 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: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 '';
          }).join('\n ');
        }
        else {
          return '';
        }
      }
    });
    
    app.dynamicHelpers({
      scripts: function(req, res) {
        return ['jquery-1.5.1.min.js'];
      }
    });
    

    the layout.ejs looks sth like this:

    
    
      
        <%= title %>
          
          <%- renderScriptsTags(scripts) %>
      
      
        <%- body %>
      
    
    

    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') %>
    
    

    <%= title %>

    I'm a template with 3 js files in the header

    that's it.

提交回复
热议问题