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

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


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.


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;  }});



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.