Passing data from Node js to HTML using EJS - javascript

Here's my Server Side code:
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
app.use(express.static('views'));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get('/',function(req,res){
var title = "PERFORMANCE OVERVIEW";
res.render('Main.html',{name:title});
})
Here's my Client Side code(Main.html):
<div class="row">
<div class="sm-col-12">
<h3 contenteditable="true" style="font-family:BentonSans Medium; text-align:center; color:rgb(0,38,99);"><%= name %></h3>
<hr style="border-top: dotted 2px;color:grey" />
</div>
</div>
The output I am getting on Main.html Page is "<%-name%>". Instead, it should print "PERFORMANCE OVERVIEW". What exactly wrong in this code?
Edit:
I forgot to mention that I have also tried other variants like <%= name%> and {{ name }}. But I am getting the output "<%= name%>" and "{{ name }}" respectively.

changing it to <%= name %> should fix it.
If that doesn't you can try changing app.set('view engine', 'html') to app.set('view engine', 'ejs');, then deleting the following 2 lines.
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get('/',function(req,res){
var title = "PERFORMANCE OVERVIEW" ;
res.render('Main',{name:title}) ;
});
I have always written it this way, so I can't say for sure if you syntax is correct, or if ejs will even work without setting it like this.
Update
Make sure the Main.html file is in a folder called views, and rename this file to Main.ejs.
next change res.render('Main.html',{name:title}); to res.render('main',{name:title});

<%- Outputs the unescaped value into the template
<%= Outputs the value into the template (HTML escaped)
As you are looking to print the value instead use <%= tag so change <%- name%> to <%= name%>
The information can be found here-https://ejs.co/#docs

Change <%- name%> to <%= name%> in your Main.html

const express = require('express');
const bodyParser = require('body-parser');
const port = 5000;
const app = express();
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
app.use(express.static('views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function (req, res) {
var title = "PERFORMANCE OVERVIEW";
res.render('Main.html', { name: title });
});
app.listen(port, console.log(`Server is running on port ${port}`))
Try this and it is rendering HTML page and also accessing the variable you pass in it.

Related

partials not being rendered express-handlebars node

I am trying to use express-handlebars and use partials but I am getting the following error message
The partial header could not be found.
My app.js code looks like as follows.
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'hbs');
app.get('/', function (req, res) {
res.render('home');
});
app.listen(3000);
This is all working and the express app is running on localhost:3000.
My folder structure is as follows:
|_app.js
|_views_
|_home.hbs
|_layouts_
|_main.hbs
|_partials_
|_header.hbs
main.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example App</title>
</head>
<body>
{{{body}}}
</body>
</html>
header.hbs
<nav>
Home
Contact
</nav>
home.hbs
{{> header}}
<h1>Hey world!</h1>
Everything works as expected until I try and introduce header.hbs as a partial.
Can anyone see any issue with my code?
Following further investigation I have also tried this, without any success:
// Create `ExpressHandlebars` instance with a default layout.
var hbs = exphbs.create({
// Uses multiple partials dirs, templates in "shared/templates/" are shared
// with the client-side of the app (see below).
partialsDir: [
'views/partials/'
]
});
// Register `hbs` as our view engine using its bound `engine()` function.
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
I believe you are missing the next line:
exphbs.registerPartials(__dirname + '/views/partials');
It was necessary to define the following settings for express-handlebars partials to work.
var handlebars = require('express-handlebars');
app.engine('hbs', handlebars({ extname: '.hbs' }));
app.set('view engine', 'hbs');
Here is the complete code:
var handlebars = require('express-handlebars');
app.engine('hbs', handlebars({ extname: '.hbs' }));
app.set('view engine', 'hbs');
app.get('/', function (request, response) {
response.render('home');
});

NodeJS Request Body Empty

I'm using node with express#4.13.4 and body-parser#1.13.3.
My jade page has for instance this property:
input(type='text',class='form-control', placeholder="Username", name='username', id="username")
The JavaScript code looks like this:
var bodyParser = require('body-parser');
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
var favicon = require('favicon')
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use( function(req, res, next){
app.locals.pretty = true
next()
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/create', function(req,res) {
res.render("create");
});
app.get('/creation', function(req,res) {
console.log("creation")
console.log(req.body)
});
The create page is the first opened and there is also the input field username, but the request body is empty in the /creation function. Can anyone help ?
You need to submit the form using POST method and alter the function:
app.post('/creation', function(req,res) {
console.log("creation")
console.log(req.body); // here will show the values of inputs submited
});
More about express routes.
As we understood body parse will work on the submit of the form or json with POST request. in this case make sure you are submitting the form correctly, you can see the POST request in firebug or other tool. Once its done correctly you will be able to see the body elements by req.body.username
you can have simple form like.
<form action='post' ..>
<input name='username' ..>
<input type='submit' ..>
</form>
Also I seen two times middleware app.use(bodyParser.json()); use. in case you missed it.

Node Ejs module, include not working

Im having some trouble including a html snippets into my index.html .
I have tried to follow, the ejs documentation but I just can't seem to make it work.
Directory Structure:
project
-public
--assets
---css
---images
---js
--Index
---index.html + index.css and index.js
--someOtherPageFolder
-views
--partials
---partials1.ejs
--index.ejs
--layout.ejs
-server.js
This is my server.js (NEW):
var express = require("express");
var partials = require("express-partials");
var http = require('http');
var path = require('path');
var app = express();
app.get("/", function(req, res) {
res.redirect("index");
});
app.configure(function(){
app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(partials());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
http.createServer(app).listen(app.get('port'), function(){
console.log('App listening on port ' + app.get('port'));
});
This is my test.ejs:
<h1>This is test!</h1>
And this is where I want the html snipp to go:
<div id="sb-site">
<div class="">
<p>Not test</p>
<%- include test.html %>
</div>
</div>
What am I doing wrong?
Is there also a way for me to do this and use .html instead of .ejs (Im using eclipse and it doesn't support .ejs files)
With include you shoud do like this:
<%- include ("./partials/footer") %>
Express 3 breaks ejs partials, use express-partials instead.
// Include it like so with your other modules
var express = require("express");
var partials = require('express-partials');
var server = express();
// Finally add it into your server conviguration
server.configure(function(){
server.set('view engine', 'ejs');
// Include partials middleware into the server
server.use(partials());
});
In your .ejs views, enjoy the luxury like so...
<%- include ../partials/header %>
<section id="welcome">
Welcome
</section>
<%- include ../partials/footer %>
Also, rather than setting the ejs module to read .html just follow this answer to get eclipse to render .ejs as .html. how do i get eclipse to interpret .ejs files as .html?
As an example, this is how a basic express structure is setup...
project
--public
--views
----layout.ejs
----index.ejs
----partials
------partial1.ejs
--server.js
server.js would look like...
var express = require('express'),
partials = require('express-partials'),
http = require('http'),
path = require('path');
var app = express();
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 3838);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Middleware
app.use(partials());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
http.createServer(app).listen(app.get('port'), function(){
console.log('App listening on port ' + app.get('port'));
});
Your route would look like...
server.get("/", function(req, res) {
res.render("index");
});
And finally, your layout.ejs...
<html>
<head>
<title></title>
</head>
<body>
<%- body %>
</body>
</html>
and index.ejs ...
<div id="index">
<%- include partial1.ejs %>
</div>
If you need a reference to the working example, here it is
You need to use the new include syntax:
before: <%- include test.html %>
after: <%- include ('test') %>

nodeJS ejs link_to undefined is not a function

The error i am getting is "undefined is not a function". I think the problem lays in the app.local part about 10 lines into app.js. I am new and following a tutorial and trying
to convert jade into ejs. I have ejs and express-helpers. I have had some issues that were solved because stuff was depreciated. The problem is with the link_to. Any ideas or anybody run into a similar problem
This is my app.js
var express = require('express');
var helpers = require('express-helpers');
var ArticleProvider = require('./articleprovider-memory').ArticleProvider;
var app = module.exports = express();
app.configure(function(){
app.locals({
link_to : helpers.link_to
});
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/public' }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
var articleProvider= new ArticleProvider();
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.ejs', {
title: 'Blog',
articles:docs
});
});
});
and my index.ejs
<html>
<body>
<h1> <%= title %> </h1>
<% for (var i = 0; i < articles.length; i++) {
var article = articles[i]; %>
<%= created_at = article.created_at %> <br>
<%= link_to(title, 'blog/'+article._id) %> <br>
<%= article.body %>
<% } %>
</body>
</html>
THe answer is here https://github.com/tanema/express-helpers
I needed
require('express-helpers')();
didn't know i needed the extra parens

Partials with Node.js + Express + Hogan.js

I'm developing a site with Node.js + Express and using as view engine Hogan.js.
This is my file app.js:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'hjs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/about', routes.about);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
The file /routes/index.js is:
/*
* GET pages.
*/
exports.index = function(req, res){
res.render(
'index',
{
title: 'Home Page',
author: 'Bruce Wayne'
}
);
};
exports.about = function(req, res){
res.render(
'about',
{
title: 'About Page',
author: 'Bruce Wayne'
}
);
};
In /views folder, there are:
|- part.hjs
|- index.hjs
|- cv.hjs
The file part.hjs is:
<h3>Hello {{ author }}</h3>
The file index.hjs is:
<h1>Title: {{ title }} </h1>
{{> part }}
Welcome to Gotham City.
And the file about.hjs is:
<h1>Title: {{ title }}</h1>
{{> part }}
I'm not Joker.
I've two questions:
How can I use properly the partials in my pages? (this code doesn't work)
Can I use the same "title" for two or more pages without repeat the values assignment in file /routes/index.js?
Best regards, Vi.
I've found a solution for the first question.
First of all, I removed hjs:
npm remove hjs
Then, I installed the package hogan-express:
npm install hogan-express
Furthermore, I edited app.js:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.engine('html', require('hogan-express'));
app.enable('view cache');
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
And routes/index.js:
exports.index = function(req, res) {
res.locals = {
title: 'Title',
};
return res.render(
'index',
{
partials:
{
part: 'part',
}
}
);
};
Now, in /views there are index.html, part.html.
The file part.html contains:
<h1>{{ title }}</h1>
The file index.html contains:
{{> part}}
Hello world!
So, It works fine.
At least in Express 4+, partials just work out of the box. You can use express-generator (from npm) with --hogan or -H option.
After doing that, you need to add partials to the render method:
router.get('/', function(req, res, next) {
res.render('index',
{
title: 'My Site',
partials: {header: 'header'}
});
});
Then, in your template use {{ > xxx }}
<body>
{{> header }}
<h1>{{ title }}</h1>
<p>Welcome to {{ title }}</p>
</body>
NOTE: this has header.hjs in views
To use partials with express+hogan, just do the following:
app.get('/yourRoute', function(req, res){
res.render('yourPartial', function(err,html){
var partialHTML = html;
res.render('yourMainView', { myPartial: partialHTML }, function(err,html){
res.send(html);
});
});
}
And now, yourMainView.html:
<p>Something Something Something</p>
{{{partialHTML}}}
<p>Bla Bla Bla</p>
Notice the triple '{' instead of double as you usually do! That telling hogan (mustache) to parse this as HTML rather then a string!
That's it.
As for your partials question, if you use consolidate.js you can simply do:
res.render('index', {
partials: {
part : 'path/to/part'
}
});
This is a problem. Partial support is difficult to come by in Express 3.
Your best bet is:
https://github.com/visionmedia/consolidate.js
npm install consolidate
These patches take different approaches to adding partials for Hogan:
https://github.com/visionmedia/consolidate.js/pull/51
https://github.com/visionmedia/consolidate.js/pull/29
Unfortunately, the engine doesn't have a hook for filesystem based partials natively, so I think people are confused about how and where partials should be implemented. I ended up with LinkedIn's Dust.js implementation, since partial support was already there. Master actually has even better support, plus I submitted a patch yesterday for relative paths.
Josh
I would use mmm instead of hjs.
https://github.com/techhead/mmm
Disclaimer: I wrote the package.
Just replace all occurrences of hjs with mmm and partials will start working. There is a lot more information and an example at the link above.
As for your other question, if you want to share properties across multiple views, you have a couple of options.
When you call res.render(name, options), the options will actually be merged onto res.locals and app.locals before being passed to the rendering engine. Therefore to set an app-wide property, you can simply assign it to app.locals.
app.locals.title = "Default Title"; // Sets the default title for the application
This concept really applies to just about any Express 3 View Engine.
However, for mmm specifically, please see the section under Presentation Logic for more ways to bind values to a template or set of templates.

Categories