I feel like the question is simple, and I'm surprised I haven't been able to find an answer, since I'm sure it's been asked before.
I am using node.js and express.js, and all I want to do is code out a single static header.html file that is included on every page. This file would have all the meta-tags and css file includes, and etc etc etc.
So when my server gets a request for website.com/blog/blog-post-3, it will
1. Load my header.html file
2. Load the content from the actual content.html file
It's the same concept as the <?php include file.html ?>....
Thanks in advance, and sorry if this has been asked before!! XD
You could do something like this :-
At node server:-
var http = require('http');
var read = require('fs').readFileSync;
http.createServer((req,res)=>{
res.setHeader('Content-Type','text/html');
res.end(new String(read('./headers.html')).replace('<my-content></my-content>',read('./content.html')));
}).listen(4000)
Headers.html:-
<html>
<!--custom css links here-->
<my-content></my-content>
<!-- custom scripts -->
</html>
Content.html:-
<body>Temp</body>
The way I've been doing it in my own app is to use a view engine that supports includes. I've been using Jade, which is now called Pug.
https://pugjs.org
With this approach you would wire up your Express app to serve your views via routes. Basically this involves setting the directory in which your views are kept, setting the view engine (Jade in my example) and defining a URL route whose response renders a view. Then in your view you would be able to define whatever include(s) you need.
Some example code (may not be complete but should give the general idea):
app.js
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', function (req, res) {
res.render('index');
});
views/index.jade - main view
doctype html
html
head
include includes/head.jade
body
...
views/includes/head.jade - include
link(href='index.css', rel='stylesheet', type='text/css')
...
Related
What is the best way to send data from a JS (that was pulled from an sqlite db) file to an HTML file to display in a searchable table. I am using NodeJS. I am fairly new so if there are to do this that take more time and code I am ok with that if it helps my learning (compared to some awesome middle wear that saves a bunch of time).
I have successfully pulled the data and displayed it to the console. I am using express as well.
Because I am new I don't want to keep using new modules the whole way through without gaining a better understanding of them. Lots of the posts I've read suggest things like ejs, ajax, jQuery and more. It would take a lot of time to start comparing them all to figure out which to use.
Any guidance on which way to go and why would be greatly appreciated.
If my question is not clear or lacking info please let me know and I'll adjust.
Assuming you have your node and express all setup, it's indeed easiest to use a template engine. It's basically a way to write HTML files, but it's easy to send data from Node.js directly to the HTML file. Since you're new to this concept, I recommend using ejs, because it looks pretty much like a regular HTML file, but with a few extra features. pug is also a well-known template engine, but this requires you to learn a new syntax.
To start using ejs, first run npm install ejs (or npm i ejs).
inside your app.js or index.js, where you setup your node and express, put
app.set('view engine', 'ejs'); above all your routes and middleware.
Inside your root folder create a folder called views. It has to be called this way.
Now inside this folder create an ejs file e.g. index.ejs.
You can read more about ejs at their website, but as I said it's just the same as HTML, the only difference being the extra values your could provide from Express.
If you want to render the index.ejs
app.get('/', (req, res) => {
res.render('index', {
data: yourdata
}
});
Here you can send the data retrieved from your database to the file. In the ejs file you can now access this data using <%= data %>. An example using a div:
<div><%= data %></div>
If your data is an array you can also iterate through using a for loop:
<% for (var item of data) { %>
<div><%= item %></div>
<% } %>
So an easy example would be
index.js or app.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.set('view engine', 'ejs');
var testData = {
test: 'test'
};
app.get('/', (req, res) => {
res.render('index', {
data: testData
})
});
app.listen(PORT);
views/index.ejs
<html>
<head>
<title>Title</title>
</head>
<body>
<div>
<%= data.test %>
</div>
</body>
</html>
And now this displays 'test' on a blank page.
This question already has answers here:
Can I link to a .ejs-page from a .html-page?
(2 answers)
Closed 5 years ago.
I am making a webpage and I have been looking on stackoverflow on how to link to .ejs-files from a .html-file.
People are saying the following
In index.html:
<li>Twitter</li>
In script.js:
app.get('/twitter',function(req,res){
res.render('twitter', { });
});
But it does not work for me. It says "Your file was not found"
However, when i put .ejs behind, like this:
<li>Twitter</li>
I can access the page, but without css. I understand that I need to create a controller so I can be able to see the css as well, but how? How can I link it so I can view it correctly? It works on localhost, but not when I first click on index.html and then click on twitter.ejs from there. I can't find any tutorials that refers to this problem.
First set your view engine as ejs.
app.set('view engine', 'ejs');
Next, tell express that your ejs files reside inside 'views' folder.
app.set('views', path.join(__dirname, 'views'));
In order to serve your static files like css,js,images,etc. Place those files in a folder eg: public. Now tell express to serve these static files:
app.use(express.static(path.join(__dirname, 'public')));
In index.html:
<li>Twitter</li>
I have recently converted my full web application from PHP to NodeJS.
In Apache, I could use a .htaccess file to perform redirects. The main redirect I had within my application was redirecting all CSS and JS files from a unique name, to their correct path. This was to make sure that when I push an update to my server, all I need to do is change the global variable to have the client load all CSS and JS files from the server instead of from the cache.
For example, in my main PHP file I would include a global variable like so:
define('js_version', "7fn39tg");
Then in my PHP file I would include all JS and CSS files like so:
<script src="content/scripts/my-script__<?php echo js_version ?>.js"></script>
They would then get rendered client slide like this:
<script src="content/scripts/my-script__7fn39tg.js"></script>
Lastly, I would then use .htaccess to read the file from it's original location, being my-script.js:
RewriteRule ^(.+)\_\_(.+)\.(js)$ $1.$3 [L]
How could I do the above in NodeJS?
I'm thinking that I need to use EJS to render the version number inside the template, like so:
app.get('/', function (req, res) {
res.render(__dirname + '/public/app.ejs', {
"js_version": "7fn39tg"
});
});
And include it in my app.ejs file like so:
<script src="content/scripts/my-script__<%= js_version %>.js"></script>
And then use app.use(function(req, res, next){.....} to somehow direct the file to it's actual path. I'm currently serving all static content from the following:
app.use(express.static(__dirname + '/public'));
You can redirect in Node using res.redirect('/redirect/path')
I want to write my HTML in HTML. Not some fancy way. The only thing that would be cool is to be able to use some sort of include statement to include header/navigation/footer for each page.
I've looked at pug, ejs, mustache, nunchuck, etc etc. I hate all of these things. I just want to write HTML..
What is a simple node module to do this? And how do I set up the render engine in my main app.js? I am using express
You can just set up your express routes to connect with html pages. Here's a simple example:
var express = require('express');
// Create express app
var app = express();
// Route index page to an index html page
app.get('/', function(req, res){
res.sendFile(__dirname + '/path/to/views/index.html');
});
// Create server
app.listen(8080, function(){
console.log('Ready on port 8080...');
});
As a side note, ejs is basically html but with some bonus functionality. You can totally get away with writing only html in ejs pages and then start using the ejs features when you get comfortable with it.
Looks like you want to server only static html files using node not some jsp equivalent dynamically generated html.
Express has support for serving static files and you do not need to define any routes for that!
http://expressjs.com/en/starter/static-files.html
Second thing I understood from your post is you want to include some common html to your html page. One way of doing that is to use a browser/client side java script framework. Take a look at angular.js. It has ng-include. Basically you can include one html file to another using that.
I currently use Jade templates within my Node project. The setup is pretty basic:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
I'm building a new part of my site with plain HTML and the HTML templates live in a different folder than the Jade templates.
My question is, how can I set things up so that I can also have an HTML view engine that serves files from a different directory (ie: not from views)?
You have couple of options.
You can just put plain HTML in a .jade file and it'll work.
Or you can setup a static router to serve HTML files directly.
app.use(express.static('./html-views'));
This way anything in your ./html-views filder will be served statically.
GET /view.html will serve ./html-views/view.html
Well, these HTML files will need to interact with your nodejs server to change values say "title".
In jade -
title=pageTitle
(ref: http://jade-lang.com/) works.
However, to get same functionality while serving HTML pages, you'll have to first serve HTML page as response to a request and then make another AJAX request to make changes to the DOM.
To serve HTML page, you can use 'fs' to readfile HTML file content and then respond with HTML content to user request or use express' function
response.sendFile('/path/to/file.html').