Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way of referencing css and js files with handlebars?

I am currently using express and handlebars for my project. It is my first time of using handlebars and I cannot figure out how to properly reference the position of my css and js files

My current project structure is like below

- test (root)
  -views
    -js
      -some JS files
    -css
      -some css files
    -layout
      -main.handlebars
  - servers.js (my server)

so I did following in my main.handlebars layout file

<!Doctype html>
<html>
<head>
    <title></title>
    {{#each css}}
        <link rel="stylesheet" href="../css/{{this}}">
    {{/each}}
</head>
<body>
    {{{body}}}
    {{#each js}}
        <script src="../js/{{this}}"></script>
    {{/each}}
</body>
</html>

And inside {{this}}, index.css goes in for css and index.js goes in for js.

But this gave Cannot GET 404 http://localhost:8000/js/index.js error. So I thought maybe handlebars look from the root somehow. so I tried

<!Doctype html>
<html>
<head>
    <title></title>
    {{#each css}}
        <link rel="stylesheet" href="views/css/{{this}}">
    {{/each}}
</head>
<body>
    {{{body}}}
    {{#each js}}
        <script src="views/js/{{this}}"></script>
    {{/each}}
</body>
</html>

But this gave Cannot GET 404 http://localhost:8000/views/js/index.js error when it looks to be the correct position of the file.

What is the correct way of referencing the js and css file in handlebars?

like image 422
forJ Avatar asked Jul 30 '17 03:07

forJ


People also ask

How do I reference CSS and JavaScript in HTML?

To link a CSS file with your HTML file, you have to write the next script on your HTML file inside the head tag. To link a Js file with your HTML, you only have to add the source of the script inside the body tag or outside; it doesn't matter.

Where do I put CSS and JS files?

You should put the stylesheet links and javascript <script> in the <head> , as that is dictated by the formats.

Can you use handlebars in JavaScript?

Handlebars. js is a Javascript library used to create reusable webpage templates. The templates are combination of HTML, text, and expressions. The expressions are included in the html document and surrounded by double curly braces.


1 Answers

You should create the public directory and in the server, you can serve static files such as images, fonts, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

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

enter image description here

Now, you can load the files that are in the public directory:

<!Doctype html>
<html>
<head>
    <title></title>
    {{#each css}}
        <link rel="stylesheet" href="/css/{{this}}">
    {{/each}}
</head>
<body>
    {{{body}}}
    {{#each js}}
        <script src="/js/{{this}}"></script>
    {{/each}}
</body>
</html>
like image 63
Burdy Avatar answered Oct 05 '22 08:10

Burdy