For some reason I can't pass a variable to the pug template with Node JS.
app.get("/", function (req, res) {
res.render('index', { hello : 'Hey'} )
})
....
extends layout.pug
block content
h1 #{hello} guy
This just returns "guy" in the index.html file
I think you are using JADE coding (#{hello}) with "pug"(updated jade) plugin with static .html -- completely wrong.
Follow the lines below:
Use this first
app.set('views', __dirname + '/public/views');
app.set('view engine', 'pug');
Then pass this to first visit
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
Then echo in template file "index.pug" in "/public/views"
html
head
title= title
body
h1= message
Try this.. works for me.
nodejs part / index.js
const router = require('express').Router();
router.get('/', (req, res, next) => {
const testObj = {hello: 'Hey'};
res.render('index', { testObj: JSON.stringify(testObj) });
});
pug/jade part / (index.pug)
script.
var testObj = !{testObj};
i'm using pug version: 2.0.3
Related
when I enter in http://localhost/client, display 404.
app.get('/client', function(req, res) {
...
ejs.render('any template', {});
...
res.end();
});
app.get('*', function(req, res) {
console.log('404');
...
});
but if I remove "ejs.render" and put res.end('any html') works.
How can i use "ejs.render" and not call 404? Thanks. It's a bug.
You need to set ejs for use EJS with express.
The Express application generator uses Jade as its default, but it also supports several others (Like ejs, pug, etc).
For example:
var express = require('express');
var app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
// use res.render to load up an ejs view file
// index page
app.get('/client', function(req, res) {
res.render('pages/index'); //does not needs ejs extension
});
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(8080);
console.log('8080 is the magic port');
When you make a request to the home page, the index.ejs file will be rendered as HTML.
See the official documentation here.
I set the page title like so for handlebars to render:
// Registor
router.get('/register', function(req, res) {
req.session.title = "Register";
res.render('register', {
active: {
active_register: true
},
title: req.session.title
});
});
I then post:
router.post('/register', function(req, res) {
The page title disappears along with all data sent when rendering the page.
I want the title to stay. How?
I have already tried resetting the title many ways with res.
According to your question there is error in handlebars. For this you have add this lines in your app.js file or main file
app.set('views', __dirname + '/views/');
app.set('view engine', 'handlebars');
app.engine('handlebars', engines.handlebars);
I am currently learning Express ( + Node.js) and I am stuck with a strange error :
Error: Failed to lookup view "index" in views directory "../NODE_tests/Tutorial/app/views"
I have an index.jade in ../NODE_tests/Tutorial/app/views
doctype 5
html
body
h1 Hellow World!
and my app.js is ( should be ) correct :
// require the stuff we need
var express = require("express");
var logger = require("morgan");
var http = require('http');
// build the app
var app = express();
// Set the view directory to /views
app.set('views', __dirname + '/views');
// Let's use the Jade templating language
app.set('view engine', 'jade');
// Logging middleware
app.use(logger('combined'));
app.all('*', function (request, response, next) {
response.writeHead(200, { 'Content-Type': 'text/plain'});
next();
});
// Express routing system ...
app.get('/', function (request, response) {
response.render('index');
});
app.get('*', function (request, response) {
response.end('404 error! Page not found \n');
});
// start it up !
http.createServer(app).listen(8080, '127.0.0.1');
running node app.js is raising this error ... where am I wrong ?
for uncleared reason the index.jade file was named index.jade.log , but .log was invisible... ( copy paste from another file...)
sorry for this unnecessary question...
discover it using OSX info on the file
Where does express get the default value for its title variable. My index.jade looks like the following:
h1= title
p Welcome to #{title}
I don't quite understand where the title variable is set.
In your routes/index.js you will be saying
res.render('index', { title: 'Express' });
So here it will find views/index.jade put value of title variable as 'Express'.
You can say in your jade
p Welcome to #{title} from #{name}
and while renderring
res.render('index', { title: 'Express' ,name: 'myName'});
it will be converted in Welcome to Express from myName.
In express, the template (.jade for example) has access to
anything in app.locals which are basically global variables
anything in res.locals which are tied to the request/response cycle of the current request
anything passed to it via res.render() which will have typically been determined in your request route handler
Just to expand on this, here is an example that should demonstrate:
app.js:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
//set a global variable that will be available to anything in app scope
app.locals.globalVar = "GLOBAL";
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.urlencoded());
app.use(express.methodOverride());
//register a middleware that will set a local variable on the response
app.use(function (req, res, next) {
res.locals.resLocalVar = new Date();
next();
});
app.use(app.router);
app.get('/', routes.index);
app.get('/:id', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
index.js:
exports.index = function (req, res) {
var id = req.params.id || "Nothing"
res.render('index', { renderVar: id });
};
index.jade:
extends layout
block content
p I am a global variable with value: #{globalVar}
p I am scoped to the current request/response with value: #{resLocalVar}
p I am only set on the call to render() in index.js and my value is: #{renderVar}
When you visit http://localhost:3000/[some value] you will see the values of app.locals.globalVar, res.locals.resLocalVar, and also the value of renderVar that's defined in the call to res.render() in index.js.
You can set view variables at the app level, the response level, and/or at the time of render.
I am using the book "Smashing Node.js" by Guillermo Rauch. Chap. 12 sets up some views/routes before an authentication example. I have followed the tutorial to the best of my ability and searched (and searched) for my error.
//package.json
{
"name": "login"
,"version":"0.0.1"
,"main":"./index"
,"dependencies": {
"express": "3.0.0"
,"uglify-js" : "2.4.0"
,"mongodb":"1.3.19"
,"mongoose":"3.6.20"
,"bcrypt":"0.7.7"
,"jade":"0.35.0"
}
}
here is my index.js
/**module dependenies**/
var express = require('express')
, mongodb = require('mongodb');
//set up app
app = express();
//middleware
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'my secret'}));
//view options
app.set('view engine', 'jade');
//app.set('views', __dirname + '/views');
//app.set('view options', {layout: false});
//routes
//default route
app.get('/', function (req, res){
console.log('default');
res.render('index', {authenticated: false});
});
//login route
app.get('/login', function (req, res){
console.log('login');
res.render('login');
});
//signup route
app.get('/signup', function(req, res){
console.log('signup');
res.render('signup');
});
//listen
app.listen(3000);
in the same directory I have a folder of views/layout.jade, index.jade, signup.jade, login.jade I will show two.
'layout.jade'
doctype 5
html
head
title BN Login
body
.wrapper
block body
and index.jade
extends layout
block body
if (authenticated)
p Welcome back, #{me.first}
a(href="/logout") Logout
else
p Welcome visitor!
ul
li: a(href='/login') Login
li: a(href="/signup") Signup
the lines I have commented out did not help or are old.
The layout.jade renders. The console shows that the code is being read. No other view is rendered.
Thanks.
I think you have not used indentation correctly. In your index this :
extends layout
block body
if (authenticated)
...
else
should be :
extends layout
block body
if (authenticated)
...
else