Marcin
Marcin

Reputation: 447

Express js and serving static files for views

I have severals views in my project let's say: "view1", "view2", "view3". View engine is "ejs". For those views I have different scripts/css files. I have also partials like: header.ejs and footer.ejs, that I am including on the top of view(header) and bottom(footer):

enter image description here

As it is in the picture view1.ejs is using two stylesheets(styleA,styleB) and scripts(scriptA,scriptB).

When I am going to use another view with those static files everything is ok because I am including header.ejs and footer.ejs inside view.

But since I am using different stylesheets and scripts for another view, and I don't want to include "styleA" and "styleB" I have a problem. I just want to keep the same partials header and footer but with another links inside.

Is there any "Assets Manager" or another solution to manage all those links?

When I want to use header.ejs in over 20pages things getting complicate, because without solution of my problem, I need to include all links/styles and some of them are not necessary.

Upvotes: 0

Views: 307

Answers (1)

LMokrane
LMokrane

Reputation: 826

In express, you can pass styles and scripts as arrays to render your ejs template :

app.get('/', function (req, res) {
  res.render('index', { styles: ['styleA.css', 'styleB.css'], scripts: ['scriptA.js', 'scriptB.js']});
});

Now update your ejs template. First the styles part :

<% styles.forEach(function(sty){ %>
   <link href="<%- sty %>" rel="stylesheet">
<% });%>

Then, the scripts part :

<% scripts.forEach(function(scr){ %>
  <script src="<%- scr %>"></script>
<% });%>

Upvotes: 2

Related Questions