I am trying to render ejs file from nodejs express.
But it shows html codes with thes character � everywhere.
let express = require('express');
let app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index', { title: 'The index page!' })
});
And index.ejs is
<html>
<head>
<title><%= title %></title>
</head>
<body>
welcome <%= title %>;
</body>
</html>
What did do I do wrong?
The server needs to be started
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index', { title: 'The index page!' })
});
app.listen(3000);
Related
I want to implement my outsourced .ejs files into the layouts/admin.ejs direction. But it throws this error. I want my outsourced header, footer and navbar to be shown. All these files are stored in /views/partials/admin/filename.ejs
My layout is in /views/layouts/admin.ejs
<%- head -%>
<body>
<!-- Navigation Top -->
<%- navigation -%>
<!-- Page Content -->
<div class="container-fluid main">
<%- footer -%>
</div>
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
so this is my app.js
const
express = require('express'),
path = require('path'),
crypto = require('crypto'),
mongoose = require('mongoose'),
multer = require('multer'),
GridFsStorage = require('multer-gridfs-storage'),
Grid = require('gridfs-stream'),
methodOverride = require('method-override'),
bodyParser = require('body-parser');
const app = express();
const port = 3003;
// Middleware
app.use(bodyParser.json());
app.use(methodOverride('_method')); // Use query string in form
// Set view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// #route get /admin
// #desc route to admin panel
const partialRoute = '/views/partials/';
app.get('/', (req, res) => {
res.render('layouts/admin', {
head: res.sendFile(__dirname + partials + 'head.ejs');
footer: res.sendFile(__dirname + partials + 'footer.ejs');
navigation: res.sendFile(__dirname + partials + 'navigaiton.ejs');
});
app.listen(port, () => {
console.log(`Server running at port ${port}`);
})
I tried to change the foldernames and routes and also removed all <% ejs but nothing works
hmmm... im using pug and not ejs, but it seems, that the directoryname is wrong/undefined?
You initialize partialRoute, but not partials?
Maybe im blind
const partialRoute = '/views/partials/';
app.get('/', (req, res) => {
res.render('layouts/admin', {
head: res.sendFile(__dirname + partials + 'head.ejs');
footer: res.sendFile(__dirname + partials + 'footer.ejs');
navigation: res.sendFile(__dirname + partials + 'navigaiton.ejs');
});
I want to increase "totalPrice" by 10 and then display it in handlebars templates . Here z some snippet of my handlebar file.
checkout.hbs
<ul class="shipping__method">
<li>Shipping <span>$ 10</span></li>
</ul>
<ul class="total__amount">
<li>Order Total <span>Rs. {{increasePrice totalPrice}}</span></li>
</ul>
For that i write this in my app.js file
var expressHbs = require('express-handlebars');
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}))
app.set('view engine', '.hbs');
expressHbs.registerHelper ('increasePrice', function (price) {
price+=10;
return price;
})
And then i got error expressHbs.registerHelper is not a function. Then i came to know to write it like this
var hbs = expressHbs.create({
helpers: {
increasePrice: function(price) {
price+=20;
return price;
}
}
})
And then i got error like "missing Helper: "increasePrice" ".
👨🏫 You see this code below 👇, an example code using express and express-handlebars:
index.js
var express = require('express');
var app = express();
var expressHbs = require('express-handlebars');
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}))
app.set('view engine', '.hbs');
var hbs = expressHbs.create({});
// register new function
hbs.handlebars.registerHelper('increasePrice', function(price) {
price+=10;
return price;
})
app.get('/', (req, res) => {
res.render('home', {
layout: false,
totalPrice: 300,
});
})
app.listen(3000, () => {
console.log('Server is up');
});
Now create file home.hbs in views, and put this code below 👇 in there.
home.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Example APP</title>
</head>
<body>
<ul class="shipping__method">
<li>Shipping: Total Price <span>$ {{ totalPrice }}</span></li>
</ul>
<ul class="total__amount">
<li>Order Total <span>Rs. {{increasePrice totalPrice}}</span></li>
</ul>
</body>
</html>
From the code above 👆, I hope you can understand now, where you have to put your function.
For an example: You can see on my codesandbox
I hope it's can help you 🙏.
I can't figure out where I messed up. When I try to render this in my browser it simply says.
ReferenceError: /views/login.ejs:14
12| <h1>
13| Value:
>> 14| <span id="val"><%= val %></span>
15| </h1>
16| </body>
17|
val is not defined
App.js (Relevant Stuff, I have Express required)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname + '/views'));
app.use(express.static(path.join(__dirname + '/public')));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(session({
secret: 'hello world',
resave: true,
saveUninitialized: true
}));
app.get('/register', routes.register);
app.post('/register', routes.postRegister);
app.get('/login', function(req, res) {
res.render('login', {
val: 'whatever'
})
});
views/login.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>
Value:
<span id="val"><%= val %></span>
</h1>
</body>
</html>
I've been stuck in this simple problem for over an hour and honestly I have absolutely no idea what it means.
Everything seems ok with the code. Probably you forgot something trivial.
This is my working setup:
var express = require('express');
// Create a new Express application.
var app = express();
// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Define routes.
app.get('/', function(req, res) {
res.render('index', {
val: 'whatever'
});
});
app.listen(process.env.PORT || 5000);
console.log("Server running at http://localhost:5000/");
I am trying to run Cheerio on node.js with ejs as my template. Whenever I run the server, I get 'undefined' at the the 'console.log'. Given below is my code.
Server side
app.js
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, request = require ('request')
, cheerio = require ('cheerio');
var $ = cheerio.load('<ul id="fruits">...</ul>');
var app = express();
console.log($('[class = "orange"]').attr('id'));
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var temp = $('[class="orange"]').attr('id');
app.get('/data', function(req, res){
console.log(temp);
res.send(temp); //replace with your data here
}).listen(3000);
index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<input type="button" id="stopButton" value="Stop Listening"/>
<p>Welcome to <%= title %></p>
<ul id="fruits">
<li id= "1" class="apple">Apple</li>
<li id = "2" class="orange">Orange</li>
<li id = "3" class="pear">Pear</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$('#stopButton').click(function () {
$.get('http://localhost:3000/data', {}, function (data) {
$('[id="2"]').text(data);
});
});
});
</script>
</body>
</html>
In the end what I wish to do is to send a value 'temp' at the press of a button 'stopButton' to the HTML page.
If you want to render html output from cheerio, cheerio describe the following way.
var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html(); // !!!You need this step!!!
Then on client side, use $('[id="2"]').html(data); instance of using $('[id="2"]').text(data);
I am working on a single page web app, and I wanted to load in jade views with my angular template but I am struggling to wrap my head exactly how to do so.
Here is my angular template:
index.html
<!doctype html>
<html ng-app="test">
<head>
<title>My Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script type="text/javascript" src="/javascripts/app2.js"></script>
</head>
<body>
<p> Hello </p>
<div>
<div ng-view></div>
</div>
</body>
</html>
I made a controller for my angular template: navigation.js
angular.module('test', [])
.config(viewRouter);
function viewRouter ($routeProvider){
$routeProvider
.when('/', {templateURL: 'views/index.jade'});
}
Here I am trying to use a jade template to render onto the page, but it does not seem to be working.
I have a view jade templates,
index.jade
extends layout
block content
h1= title
include partials/menu
.views-wrapper
include partials/login
layout.jade:
doctype
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
script(src='//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')
script(src='/javascripts/navigation.js')
menu.jade:
ul
li.a VIEW A
li.b VIEW B
li.c VIEW C
li.l VIEW LOGIN2
I also have a view simple templates (named a.jade, b.jade, and c.jade) which just have simple headers displaying a name as a test to see if the routing works. I am struggling to get these templates to connect, I can't seem to wrap my head around, nor find an answer as to how I can display my jade views through my angular template. Before I was not using an angular template, but decided to use one in order to deal with URL more easily.
this is my app.js on my server side:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
app.use(express.cookieParser('cookies monster')); // Cookie secret
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.set('public', path.join(__dirname, 'public'));
/*
* Views
*/
//app.get('/', routes.index);
app.get('/', function(req, res, next){
return res.sendfile(app.get('public') + '/index.html');
});
app.get('/users', user.list);
app.get('/a', routes.a);
app.get('/b', routes.b);
app.get('/c', routes.c);
app.get('/login2', routes.login2);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
and this is a routes controller that I had to render the views before I decided to use angular
index.js:
exports.index = function(req, res){
res.render('index', { title: 'New Test' });
};
// View A
exports.a = function(req, res) {
res.render('partials/a', { layout: false, test: 'a' });
};
// View B
exports.b = function(req, res) {
res.render('partials/b', { layout: false, test: 'b' });
};
exports.c = function(req, res) {
res.render('partials/c', { layout: false, test: 'c' });
};
exports.login2 = function(req, res) {
res.render('partials/login2', { layout: false, test: 'login2' });
};
I know this is a lot of code to look at, but I would really appreciate any help.
Check my answer on stackoverflow about using AngularJS seed for working with Jade, it can help you with your question.