Basic html engine in Node - javascript

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.

Related

Running on Nodejs, how to send data from JS file to HTML -- need advice on all the diff modules

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.

How to trigger onclick function in router for PugJS?

I'm currently using a expressJs template that uses pug in order to make a simple website. On the site is a button. I want on the click of the button to call a function in the index.js file.
Originally I had the code like this. In the index.pug file:
extends layout
block content
h1= title
p Welcome to #{title}
button#BubbleButton.button.hypeButton.button-3d.button-caution.button-circle.button-jumbo(onclick = 'buttonClick()') Click
In my index.js file, it would look like so:
var express = require('express');
var router = express.Router();
var PubNub = require('pubnub');
module.exports = router;
function buttonClick(){
alert('test');
}
However, I would get a response along these lines:
buttonClick function not found.
I'm frankly more familiar with angular than pug. What does it take to link up the view side to the router file? I understand in Pug, you can add an endpoint REST API style, but this isn't necessarily going to be an API. I may just want to show something simple and not expose it. However, I may be misunderstanding something fundamental.
Thanks!
The JavaScript code contained in the script. tags in your pug file will only run in the browser, and the code in index.js will only run on the server. Therefore they can never speak directly.
You need an ajax call on the client (i.e. in your pug file). Here's an example using jquery but you can use one of the many ajax client packages out there to do the same thing:
script.
function onButtonClick(){
$.ajax({
"url": "/service",
"method": "POST"
});
}
Then you need a route handler in index.js:
router.post('/service', function(req, res){
console.log('test');
});
Note that this will output to the console on the server, not the client. I believe that's what you want to do.
To add jquery to your page you can use a cdn (Content Delivery Network) to quickly bring it into your code. Here is the pug syntax for that:
script(src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous")
Alternatively you could you axios as a lightweight alternative to jquery, all it does is ajax:
script(src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js" integrity="sha256-mpnrJ5DpEZZkwkE1ZgkEQQJW/46CSEh/STrZKOB/qoM=" crossorigin="anonymous")

Global Header file Node.js & Express.js

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')
...

Providing auth for static HTML/JS application with Sails.js

I have a client side application written in plain HTML/JS (Not with Angular.js or other front-end MVC framework). It contains multiple html file. each includes different js library.
I would like to provide basic user auth feature(using sails-generate-auth) to limit the access of this client-side application using Sails.js
But I'm having problem putting those html file into /views
Should I change all *.html in to *.ejs and edit /config/routes.js to route each file? How do I make use of the req.session.authenticated ? Please provide some direction. Thank you.
Your solution written in your question would work. Here is another option:
You can send the file straight from your controller or for universal usage you can create a custom response that will send the html file instead of attempting to render the ejs view. Call it sendHtml(), or modify the current ok.js to know and send your html files
http://sailsjs.org/#!/documentation/concepts/Custom-Responses
Use something like
res.sendfile('/views/' + rest.controller + '/' + res.action + '.html');

Cloud 9 ide post data to page not working

I am developing a small node.js application using express on Cloud 9 ide.
I have a static index.html page and some routes defined. One of the routes is a post
app.post('/getJson', function (req, res) {
jsonData = fetchData(req.body.selectpicker);
res.render('index.html', '<p>tttt</p>');
});
As jade is not supported i just want to pass some html to the static page. Currently using
res.render('index.html', '<p>tttt</p>');
How can I render the html on the page?
The render() function of the response renders a view and returns the HTML. If you want to render pages, you need a rendering engine such as EJS or Jade. If you're using either of those rendering engines, you can pass the HTML like so:
res.render('index.html, {
html: '<p>tttt</p>'
});
Since Jade isn't supported (may I ask why?), this is how you'd insert the HTML fragment in EJS.
<p><%=: html %></p>

Categories

Resources