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

pkyeck picture pkyeck · Jul 7, 2011 · Viewed 20.9k times · Source

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)

layout.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <link rel='stylesheet' href='/stylesheets/smoothness/jquery-ui-1.8.14.custom.css' />
  </head>
  <body>
    <%- body %>
  </body>
</html>

index.ejs

<h1><%= title %></h1>
<p>Welcome to <%= title %></p>

i don't want to add the second css file in every template but only the index.ejs - is there any way i can do that?

Answer

pkyeck picture pkyeck · Jul 8, 2011

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.