6

I come from a PHP background, but am deciding to try out NodeJS (and probably Express) on my latest project. What is an alternative to PHP includes for templating HTML pages? I'm used to doing:

<?php include('header.php'); ?>

I've tried googling and searching Stack Overflow, but can't find NodeJS's alternative.

LearnSomeMore
  • 440
  • 4
  • 12
  • 1
    Getting PHP like functionality where you just want the HTML to be included from a separate file you can do this: `express.get('/', function (req, res) { let header = fs.readFileSync(__dirname + '/header.html'), index = fs.readFileSync(__dirname + '/index.html'); res.send(header + index); });` – Got To Figure Feb 27 '18 at 17:47

1 Answers1

3

If you want to load only exported objects from external file, you can use require function.

var imported = require('your-module');

If you want to execute external Javascript file directly into your global scope (similar to PHP's include), then you should use eval.

eval(require('fs').readFileSync('your-module\\index.js') + '');
  • I'm looking for something that would allow a "templated" html page. That way I can change the header of the document and all of the headers would change. – LearnSomeMore Aug 21 '16 at 00:36
  • I am not sure what you want to do. Node.js doesn't have headers, it uses modules instead. If you change module, all scripts which include that module will be changed. –  Aug 21 '16 at 00:38
  • Sorry, maybe NodeJs isn't the right technology to do this. Do you know of a way to include HTML files in HTML files? For example, if I have a website header that is on all of my HTML pages. – LearnSomeMore Aug 21 '16 at 00:42
  • @LearnSomeMore. The best way to do it in a HTML is to include a script which will configure headers when `window.onload` event fires. –  Aug 21 '16 at 00:44
  • On a side note - the eval solution mentioned here is a great parallel to PHP to include functions and clean up your base script. – Andrew Feb 06 '20 at 21:50