Unable to include CSS styling in handleBar templates with Node Js App

Viewed 1178

I have a Node Js-Express Based app and using handlebars template to design a structure for Nodemailer HTML body. I tried including the CSS file multiple ways for the same, but still none of the styles are being applied to the HTML.

My current project structure is something like this:

- backend
  - src
  - helpers
    - templates
      - emailTemplate.handlebars
  - public
    - styles.css
  - app.js

The app.js is defined to use the handlebars like this:

const express = require('express');
const app = express();

app.use(express.static(path.join(__dirname, '/public')));

The handlebar template goes like this:

<html>
<head>
    <title>Update Project Details</title>
    {{#each css}}
    <link rel="stylesheet" href="../../public/{{this}}">
    {{/each}}
</head>

<body>
    <h1>{{headerMessage}}</h1>
    <p>{{message}}</p>
    <p>
        {{bodyText}}
    <div class="row">
        <div class="side">
            <button class="edit"> Edit Details </button>
        </div>
        <div class="main">
            <button class="archive"> Archive Product </button>
        </div>
    </div>
</body>
</html>

As the nodemailer functions and mail is received, the HTML content is rendered from the HandleBar template inside the mail body, but without any CSS or styling.

I also tried keeping the CSS file inside the same folder as the template, but no luck. Not sure where I'm going wrong. Any help to resolve the same will be highly appreciated.

1 Answers

the only issue that I see here is the actual linking up of the style sheet to your DOM. If you look at the app.use in your app.js where it says:

app.use(express.static(path.join(__dirname, '/public')));

that means that any so called "public" files, images, local js, style are stored in the public folder, and that is the new relative path for all headers. So no matter where your ejs or html file is, the relative path to the style sheet will always be from the top level down of your public folder. This makes it more dynamic and the only thing you have to change is:

<link rel="stylesheet" href="../../public/{{this}}">

to:

<link rel="stylesheet" href="{{this}}">

Simple as that. Hope this makes sense, happy coding!

Related