I'm working on a scaffolding project for simple, no cms, html sites. Basically, the site runs off a simple node server, running express & handlebars, with handlebars .hbs template files and a main.hbs as the main layout. This is all for development purposes. When the site is ready to be pushed up somewhere, I want a build task that will render it into a completely static html site.
My Problem: I can't figure out how to get the html of a fully rendered page, from my handlebars templates, loaded into a node module I can then create HTML files from using the module like a build task eg. node Build.js. Here is some code to show you, basically, the main layout and home layout need to be compiled then given to me as a js string.
PS. I have the regular handlebars package aswell, I'm just using express-handlebars for the server part.
server.js (irrelevant parts taken out)
// -----------------------------
// Dependancies
// -----------------------------
// https://www.npmjs.com/package/express
var express = require('express');
// https://www.npmjs.com/package/express-handlebars
var exphbs = require('express-handlebars');
// -----------------------------
// Template Engine
// -----------------------------
// Specify template engine & it's config
app.exp.engine('.hbs', exphbs({ extname: '.hbs', defaultLayout: 'main' }));
// Set the engine defined above
app.exp.set('view engine', '.hbs');
// -----------------------------
// Apply the routes to our application
// -----------------------------
app.exp.use(express.static(__dirname), app.router);
// -----------------------------
// Routes
// -----------------------------
// Home Route
app.router.get('/', getRoute);
// Route Controller
app.router.get('/:page', getRoute);
// Formats page data and renders the template
function getRoute(req, res) {
// If homepage, set some data
if(req.url === '/') req.params.page = 'home';
// Capitalize the route param for the page title
var title = req.params.page.substr(0,1).toUpperCase() + req.params.page.substr(1);
// Render the view
res.render(req.params.page, {
name: app.name,
title: title,
class: req.params.page
});
}
app.exp.listen(app.port);
Main layout (the standard html guts, the {{body}} data is where the template files are loaded into)
<!doctype html>
<html lang="en">
<head>
<title>{{title}} - {{name}}</title>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta charset="utf-8">
</head>
<body class="page-{{class}}">
<!-- Navigation -->
{{> nav}}
<!-- Page Content -->
<main>
{{{body}}}
</main>
</body>
</html>
And just for example, the home template
<div>
<p>
This is the homepage.
</p>
</div>
Related
I wanted to know are there any application scope variables that can be accessed anywhere in the whole application.
Since I want to add data to my HTML tags using javascript, I need to transfer/get data from the server.js to the index.html
To transfer data from server.js to index.html you don't need to create global variables. You need to use a templating engine: pug, ejs or any other engine.
Just pass the data along with html file in the res.render() function and use templating syntax to display the data at the page.
Router code:
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
Pug code:
html
head
title= title //Hey
body
h1= message //Hello there!
ejs code:
<html>
<head> <%= title %> </head>
<body>
<h1> <%= message %> </h1>
</body>
</html>
I am learning node and using expressjs the problem is that the css file is only working on the main page and not any other page following is the code for the app:
var express = require("express");
var app = express();
// assets
app.use(express.static("public"));
// simple file testing
app.get("/anything/:stuff", function(req, res){
var stuff = req.params.stuff;
res.render("love.ejs", {stuff: stuff});
});
// posts page
var books = [
{title:"Harry Potter",author:"JK Rowling",editions:7},
{title:"Peere Kamil",author:"Humaira Saeed",editions:4},
{title:"Mushaf",author:"Abdullah khan",editions:2}
];
app.get("/books", function(req, res){
res.render("books.ejs",{books:books});
});
app.listen(3000, process.env.IP, function(){
console.log("Serving Now!");
});
The following is the code for the page where it is not working.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="app.css" />
<title>demo app</title>
</head>
<body>
<h1>You fell in love with : <%= stuff %> </h1>
<%
if(stuff.toUpperCase() === "WAQAS"){ %>
<P>GOOD CHOICE HE IS THE BEST</p>
<% } %>
<p>P.S This is the love.ejs file</p>
</body>
</html>
The file is under public directory.
Use an absolute URL for the CSS file, so the browser doesn't look for it relative to the current URL:
<link rel="stylesheet" href="/app.css" />
Explanation: say that you open the URL /anything/helloworld in your browser. When your HTML contains just app.css, without the leading slash in front of it, the browser will try and load /anything/app.css (because without that slash it's relative to the current URL), which doesn't point to your CSS file.
When you add the leading slash, express.static will be able to find the CSS file in public/.
I am using express and ejs to build a website:
"dependencies": {
"ejs": "^2.5.2",
"express": "^4.14.0",
in my app.js I have defined ejs as template engine and the root of views:
app.set('view engine', 'ejs'); // set view engine
app.set('views', 'app/views'); // set custom root for view engine
I then created my index.ejs file in which I included a partial from a subdirectory:
index.ejs
<head><% include ./partials/template/head %></head>
folder structure:
- views
index.ejs
-- partials
-- -- template
head.ejs
When a start the server, index is loaded without errors but without the head section.
If I change the include (pointing to a wrong location) the server fails to start highlighting the problem, so ejs is able to locate the head.ejs.
if I move head.ejs in the views directory the head is correctly loaded in the index.ejs.
So... I am a bit puzzled, it seems that in the subdirectory the file read but not loaded into the include.
After searching for around I tried using express-partials but it has not helped much.
Any clue?
Cheers, Giovanni
just change your include statement like this
<%- include("./partials/template/head.ejs") %>
this worked for me.
With Express 4.0
<%- include header.ejs %>
this worked for me.
I've never used an EJS template in <head> section.
I use ejs and express-ejs-layouts packages together.
So if you want to create a top division which would be fixed and appears on every different page (maybe a navigation part), you might create a main layout ejs for your application.
When I render an EJS on a route by using res.render('index'), rendered EJS page (index.ejs in my case) replace with <%- body %> parts in the example below.
And I use a navbar.ejs file with <% include navbar %> line. And the navbar is shown on the top of the page at every page, fixedly.
Example
app.js - needed variables, settings and middleware
var express = require('express')
var expressLayouts = require('express-ejs-layouts') // to use EJS layout
var app = express()
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(expressLayouts) // EJS Layout.ejs
layout.ejs file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<% include navbar %>
<%- body %>
<% include page_footer %>
</body>
</html>
with express 4.0 using "ejs-mate module
In app.js
// Khởi tạo express
var express = require('express');
var app = express();
var engine = require('ejs-mate');
var port = process.env.PORT || 3000;
// Khởi tạo public, view engine...
app.use(express.static(__dirname + "/public"));
// Sử dụng đuôi html
var ejs = require("ejs");
app.set('view engine', 'ejs');
app.engine('ejs', engine);
// Cấu hình thư mục views
app.set("views", __dirname + '/views');
// Khởi tạo Web Server
var server = app.listen(port, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
app.get('/Admin', function (req, res) {
res.render('./admin/layout.ejs');
});
In layout.ejs
<html>
<head>
<%-partial('./sub-folder/header')%>
</head>
<body>
<-- -->
<h1>
buiducanh.net
</h1>
<%-partial('./sub-folder/footer')%>
</body>
</html>
I believe the problem to be not related to subfolders. If you look at your code:
<head><% include ./partials/template/head %></head>
We can see the include directive is used which will invoke the templating engine and return the html that you desire to render in your <head /> section of index.ejs.
However it doesn't get rendered simply because you forgot to include a "-", which tells it to actually print the contents into that section of html, you can also use a "=" which does the same thing only escaped.
So to fix you should edit your index.ejs as follows:
<head><%- include ./partials/template/head %></head>
Notice the inclusion of the "-" following the "<%".
Hope this helps.
Im trying out EJS as a view engine with Express. It seems that my layout.ejs is not used. I have two views index.ejs and layout.ejs both in my 'views' folder. It seems that index.js is rendered but layout.ejs is not. The layout.ejs file should be including a CSS file but when the page is rendered in the browser this is not there. Any test test text that I place in the layout.ejs file is not output with the response.
Am I missing an additional configuration step?
Thanks!
My server.js code:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.ejs', {title: 'EJS Engine'});
});
app.listen(8080);
In my layout.ejs I am linking to a single css file which resides in the public folder.
layout.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<%- body %>
</body>
</html>
index.ejs
<div id="container">
index.html
</div>
Here's the module you need:
https://www.npmjs.org/package/express-ejs-layouts
Do the following:
npm install express-ejs-layouts // install the layout module from the command line
var express = require("express")
,path = require('path')
,fs = require('fs')
,expressLayouts=require("express-ejs-layouts") // add this requirement
, app = express();
app.use(express.bodyParser());
app.use(expressLayouts); // add this use()
app.use(express.static(__dirname));
Now the ejs engine should use your layout.
app.set('view options', { layout:'layout.ejs' });
Place layout.ejs into your views folder.
Alternately you can place layout.ejs into views/layouts folder and then use
app.set('view options', { layout:'layouts/layout.ejs' });
I have a similar issue. In my case I would rather use Jade but I have a requirement for a more "html" style template engine for a particular project. At first I considered express-partials or ejs-locals (as mentioned in a comment by Jonathan Lonowski) or even using html via the pipe or dot syntax within Jade templates (see here for more information about that option and this SO post). I am not able to introduce the additional dependencies for express-partials and ejs-locals into this project. These two projects do look good and might meet your needs.
If you do not want to use these projects, you can do something like the following:
views/layout-head.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The title</title>
</head>
<body>
views/layout-foot.ejs
</body>
</html>
views/index.ejs (or any other page)
<% include layout-head %>
This is the index page - <%= title %>
<% include layout-foot %>
routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'Express' });
}
This is not an optimal solution but it works. Most of my application will be a single page app and I have some other restrictions I have to work within so this works for my needs. This may not the best solution in many cases - especially if you have complex and/or changing layouts.
I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.
Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />
in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />
Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.
With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>