Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS include header and footer without EJS

I was hoping someone may be able to assist me with NodeJS. Iv recently started developing my site using NodeJS.

The problem:

im looking for a way to send my documents as a header, content, footer style so it reduces repeating code for each section.

I have a public folder setup so i can include Js, CSS and common files etc...

self.app.use(express.static(__dirname + '/public'));

This all works, however im unsure about how to implement a simple way to join the file content. Every source iv looked at online suggests the "correct" way to do it is via a package called EJS templates.

So im looking for something similar to this implementation in EJS:

<header>
    <% include ../partials/header %>
</header>

<footer>
    <% include ../partials/footer %>
</footer>

However, the service im hosting on does not support EJS, so is it possible to do something like this?

self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('header.html')+self.cache_get('index.html')+self.cache_get('footer.html') );
        };

Is there another simple way to separate header, content and footer to make it simpler to develop website with dynamic content?

like image 708
D3181 Avatar asked Jan 06 '23 09:01

D3181


2 Answers

Trumpet should let you do this. Something like this may work:

const trumpet = require('trumpet')
const tr = trumpet()

tr.pipe(res)

const header = tr.select('header').createWriteStream()
fs.createReadStream('header.html').pipe(header)

const footer = tr.select('footer').createWriteStream()
fs.createReadStream('footer.html').pipe(footer)

fs.createReadStream('index.html').pipe(tr)
like image 69
Jekrb Avatar answered Jan 07 '23 21:01

Jekrb


While you could write your own js to do this, at your current level I don't recommend it (other than for learning and experimental purposes). This is why node is so powerful, because you don't have to reinvent the wheel all the time. You noted that you are using openshift, and that you cannot use modules. This is where you are incorrect.

This link explains how to use npm with openshift. It would be extremely silly for any node.js hosting service to not allow package integration. To briefly explain how this works, you essentially install your packages in your local environment using the --save flag. This will update your local package.json file with details about your dependencies and versions. When you push your repo to your host, it looks at this file, and takes care of the dependency installation for you.

On this note, if you are going to continue using node.js, you should have a good read about package management. https://docs.npmjs.com/how-npm-works/packages

like image 21
Matt Way Avatar answered Jan 07 '23 21:01

Matt Way