How to add styles(css) and js to handlebar files?

10.6k Views Asked by At

I want to add styles and js to my handlebar files. I tried looking for different places but still not able to find a solution. I tried using partials to store the stylesheet tags then adding those partials to handlebar but that too didn't worked. (Or if there is any other templating engine that provides much better css support, that too will work for me) Please Help!

styles.hbs (partial file)

<link rel="stylesheet" href="./../css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="./../css/main.css">

server.js

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

var app = express();

app.set('view engine', 'hbs');
hbs.registerPartials(__dirname + '/views/partials');

app.get('/', (req, res) => {
    res.render('index.hbs');
});

app.listen(3000, ()=>{
    console.log('Server is up at port 3000');
});

index.hbs

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Home Page</title>

    {{> styles}}
  </head>
  <body>
   ...
  </body>
</html>
1

There are 1 best solutions below

0
On

This is an old question but still confusing. Here is the most effective way to use different css file in your views:

main.hbs (Your base layout)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="mainstyle.css">
    <!-- mainstyle.css will be effective in all pages-->
    {{{customstyle}}}
    <title>{{title}}</title>
</head>
<body>
    {{body}}
</body>
</html>

Please pay attention {{{customstyle}}} line in main.hbs

app.js

...
app.use((req, res) => {
    res.status(404).render("404page", {title:"404 not found",
    customstyle: `<link rel="stylesheet" href="/css/customstyle.css">`});
});
...

Thats it. As you know, {{{ }}} renders as html code, but {{ }} renders as only text in handlebars. customstyle passes as an argument to main.hbs layout file. We used three curly brackets in main.hbs file, because of we wanted to process the argument we send as html code. In this way, customsytle.css file added only when 404page viewed.