Node Ejs module, include not working - javascript

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

Related

Passing data from Node js to HTML using EJS

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.

Handlebars/Node/Express Can't load files

So I'm working on developing a Node/Express webapp for basic CRUD operations and I'm having a hard time implementing Handlebars within the project.
When I try to use handlebars none of my stylesheets from my .hbs (previously .html) pages are loading.
Here's the file tree:
Here is the error:
And here is an example of the script import statements from
index.hbs
<!-- Bootstrap -->
<link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
And Finally here is the server.js file
var express = require('express'),
bodyParser = require('body-parser'),
path = require('path'),
mysql = require('mysql'),
dbconfig = require('./config/database'),
exphbs = require('express-handlebars');
var connection = mysql.createConnection(dbconfig.connection)
connection.query('USE ' + dbconfig.database);
var app = express();
//Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//Set static path
//app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static(__dirname + '/public'));
//app.set('views', __dirname + '/views');
//app.use('/views', express.static(path.join(__dirname, '/views')));
app.engine('hbs', exphbs({defaultLayout: false}));
app.set('view engine', 'hbs');
app.set(express.static(__dirname + '/public'));
//app.use('/views/vendors', express.static(path.join(__dirname, '/views/vendors')));
//app.use(express.static(__dirname + '/public/vendors'));
app.get('/', function(req, res) {
res.render('index');
connection.query("SELECT * FROM Student", function(err, rows){
console.log(rows);
});
});
app.listen(80, function() {
console.log('we are live on 80');
});
I tried using various static paths from other things I found on SO but wasn't able to get any of them to work.
Any help would be greatly appreciated!!
Thanks!
Fixed my problem by adding the following line above my app.get('/'....
app.use("/vendors",express.static(__dirname + "/vendors"));
app.use("/build",express.static(__dirname + "/build"));
app.use("/images",express.static(__dirname + "/images"));
app.get('/', function(req, res) {
I think that can be possible that the problem is in the handlebars configuration, please look at a configuration like this:
app.engine('.hbs',exphbs({
defaultLayout:'layouts',
layoutsDir:path.join(app.get('views'),'layouts'),
partialsDir:path.join(app.get('views'),'partials'),
extname:'.hbs',
helpers: helpers
}));
app.set('view engine','hbs');
maybe in yours it would be:
app.engine('hbs', exphbs({defaultLayout: false, extname:'.hbs',}));
if you are usign app.set(express.static(__dirname + '/public'));
try to put in the public folder your styles for example the bootstrap folder, and then all you have to do is call it in this way:
<link href="/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

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');
});

Not loading custom scripts from public folder Express (generator)

I am a newbie to node and express and I am really stuck right now. I want to load a custom script.js form the public folder but it doesnt seem to load. Nothing in the network tab, no errors in the console. When I to go the url: localhost:3000/javascripts/script.js, I am seeing the code. I tried every answer given on SO, but nothing seems to work. Using the express generator. What am I doing wrong here.
See code:
app.js
var express = require('express');
var path = require('path');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
index.ejs file
<html>
<head>
<!-- include head -->
<% include partials/head.ejs %>
</head>
<body>
<% include partials/header.ejs %>
<% include partials/footer.ejs %>
<script scr="/javascripts/script.js"></script>
</body>
</html>
index.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
<script scr="/javascripts/script.js"></script>
should be
<script src="/javascripts/script.js"></script>

Express js external javascript file not loading

I use an express app to serve an static pre-compiled jade file. which includes a external javascript file. but its not loaded while the page gets loaded. but i can access the javascript by the express static/public url. Why its not loading on the html?
app.js
var express = require('express'),
path = require('path'),
sass = require('node-sass');
var app = express();
/* default configurations */
app.set('views', __dirname + '/public');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
/* routes */
app.get('/', function(req, res) {
res.send('Hello World');
});
app.get('/home', function(req, res) {
res.render('index.html');
});
module.exports = app;
index.html
<body>
<script type="text/javscript" src="/scripts/site.js"></script>
<script type="text/javascript">
window.onload = function() {
Site.View.init();
}
</script>
</body>
site.js
var Site = Site || {};
Site.View = {
init : function() { alert('view'); }
};
When i open the page in browser i get ReferenceError: Site is not defined
Thanks.
Add app.use('/public/js', express.static(path.join(__dirname, '/public/scripts'))); to app.js, in order to indicate the subfolders of the pulic folder;
If it still not works, change src="/scripts/site.js" to src="/public/scripts/site.js";
site.js must be inside public/scripts from your root directory.
I am not sure but both views and express static pages are gone to public directory in your code.
Use default configuration as:
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
You may also add a route for it like this:
app.get('scripts/site.js', function(req, res){
res.send('./scripts/site.js');
}

Categories