How I can append js into a express handlebars template using partial? - javascript

In my project I use the following handlebars template (under views/layouts/main.handlebars) :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{title}}</title>
{{{css}}}
{{{js}}}
</head>
<body>
<header>
<!-- some content here -->
</header>
<main>
{{{body}}}
</main>
<footer>
I am footer
</footer>
</body>
</html>
And for my home page I made a simple content named ./views/home.handlebars
<h1>Hello</h1>
In order to render the template I use express handlebars:
const express = require('express');
const path = require('path');
const express_handlebars = require('express-handlebars');
const app = express();
const hbs = express_handlebars.create({
// Specify helpers which are only registered on this instance.
defaultLayout: 'main'
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views',path.join(__dirname,'/../../views'));
app.get('/', (req, res, next) => {
res.render('home');
});
app.listen(3000);
What I want is to place some javascript once I visit http://0.0.0.0:3000 for example:
<script>alert("Hello");</script>
Where I want to be appended is in {{{js}}} partial. Is there a way to do it?

An approach of mine is to make the js section as an array and place a base html5 tag, specifying where each page will find its js:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{title}}</title>
{{{css}}}
{{#each js}}
<script src="{{this}}"></script>
{{/each}}
</head>
<body>
<header>
<!-- some content here -->
</header>
<main>
{{{body}}}
</main>
<footer>
I am footer
</footer>
</body>
</html>
For my application's js I use separate files per page and I do not embed it inside my homepage into a folder named static:
const express = require('express');
const path = require('path');
const express_handlebars = require('express-handlebars');
const app = express();
const hbs = express_handlebars.create({
// Specify helpers which are only registered on this instance.
defaultLayout: 'main'
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views',path.join(__dirname,'/../../views'));
app.use('/static',express.static(path.join(__dirname,'/../static')));
app.get('/', (req, res, next) => {
res.render('home',{
title:'Homepage',
js: [
'/static/js/home.js'
],
baseUrl: `${req.protocol}://${req.get('host')}`
});
});
app.listen(3000);
Then upon static folder I place the necessary js files that will run upon the browser. I found it as an easy-peasy solution and keep client-side js into its own folder.

Related

Node.javascript get on local host

I'm trying to follow a video but still can't get when I load by local host in the web browser.
I am get a console log of listening at 3000 but it seems that this line:
"app.use(express.static("/Users/name/Desktop/Weather App/public/app.html"));" is not working.
Any suggestions?
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("listening at 3000");
});
app.use(express.static("/Users/name/Desktop/Weather App/public/app.html"));
This the code Im using now.
server.js
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile(
"/Users/name/Desktop/Weather App/public/app.html"
// "/Users/name/Desktop/Weather App/public/style.css"
);
});
// serve any HTML files located in /Users/name/Desktop/Weather App/public
// app.use(express.static("/Users/name/Desktop/Weather App/public"));
app.listen(3000, () => {
console.log("listening at 3000");
});
app.html
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
</head>
<body>
<h1>Weather App</h1>
<div id ="container">
<p>
Place: <span id = "places"></span><br/><br/>
Temperature: <span id="temperature"></span>&degC<br/><br/>
Feels like: <span id="feels"></span>&degC<br/><br/>
Minimum Temp: <span id="min"></span>&degC<br/><br/>
Maximum Temp: <span id="max"></span>&degC<br/><br/>
Humidty: <span id="hum"></span>&percnt;<br/>
</p>
<div>
<input id="inputter" type="text" ></input><br/><br/>
<button id="entButton">Click here for weather forecast</button><br/><br/>
<button id="geoEnter">Click here for fast weather</button><br/>
</div>
</div>
<div>
</div>
<script href="/Users/name/Desktop/Weather App/server.js"></script>
<script src="/Users/name/Desktop/Weather App/public/app.js" ></script>
<link href="/Users/name/Desktop/Weather App/public/style.css" rel="stylesheet" type="text/css"/>
</body>
</html>
any suggestions?
If you just want app.html to show when http://localhost:3000 is the URL, then you can do this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile("/Users/name/Desktop/Weather App/public/app.html");
});
app.listen(3000, () => {
console.log("listening at 3000");
});
If you have more files in /Users/name/Desktop/Weather App/public that you want to automatically serve to the client when requested, then you can add this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile("/Users/name/Desktop/Weather App/public/app.html");
});
// serve any HTML files located in /Users/name/Desktop/Weather App/public
app.use(express.static("/Users/name/Desktop/Weather App/public"));
app.listen(3000, () => {
console.log("listening at 3000");
});
So, if styles.css was located in /Users/name/Desktop/Weather App/public, then a URL for /styles.css would automatically serve the file /Users/name/Desktop/Weather App/public/styles.css.
Change the links in your app.html page to this:
<script src="/app.js"></script>
<link href="/style.css" rel="stylesheet" type="text/css"/>
The URLs in these tags need to be relative to the directory specified in your express.static() file and will usually start with a / so they are independent of the containing page URL.
The file system path supplied to express.static is too long.
express.static takes a directory path argument, not a file path. If the get request to the static server endpoint does not include a filename on the end (e.g. ".../app.html) express static middleware looks for a configurable default file name (initially set to index.html) for content to serve.
See also express.static documentation and in particular the index and extensions properties of the options object.

nunjucks: Error: template not found, Problems with directories

Sorry if I report with a problem that has been dealt with frequently in the forum.
I get the error message that the template was not found.
Error: template not found: D:\Development\src\nunjucks\pages\templates\text.njk
What am I doing wrong with the directory structure specification?
Is there a way how to generate html files from nunjucks files like gulp? With gulp it works.
This is the script for node.js:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const nunjucks = require('nunjucks');
app.use(express.static('dist'));
nunjucks.configure('src/nunjucks', {
autoescape: true,
express: app,
watch: true
});
app.engine ('njk', nunjucks.render);
app.set('view engine', 'njk');
app.get('/', (req, res) => {
res.render('pages/index2');
console.log("index");
})
server.listen(3010, () => {
console.log('http://localhost:' + 3010);
})
And this is the directory structure:
app.js
gulpfile.js
|-src
| |-nunjucks
| |-pages
| | index.njk
| |-templates
| text.njk
And this is the index.njk file:
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<h1>Header Test</h1>
{% include "text.njk" %}
</body>
</html>
All your templates will be resolved from the path(s) you a passing to nunjucks.configure.
In your case you should include template with path from src/nunjucks.
E.g.templates/text.njk.
That is the solution in the script for node.js
nunjucks.configure('src/nunjucks', {
autoescape: true,
express: app,
cache: false,
watch: true
});
// app.set('views', 'src/nunjucks/pages');
app.engine ('njk', nunjucks.render);
app.set('view engine', 'njk');
app.get('/', (req, res) => {
res.render('pages/index.njk');
})
app.get('/index.html', (req, res) => {
res.render('pages/index.njk');
})
And the index.html file
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<h1>Header Test</h1>
{% include "../templates/text.njk" %}
</body>
</html>

Not reading the CSS - Express ejs layouts

I am using the express ejs layouts but only the mainPage can read the css the other pages don't read it (the css, the html read it).
Another question, if I wanted to use another layout (ex: layout2.ejs) what would i do to act on a specific page.
Tree:
Project
- public
- js
- css
- style.css
- routes
- index.js
- users.js
- views
- layout.ejs
- mainPage.ejs
- login.ejs
...
- app.js
I am using particles.js if you need to know.
app.js
const express = require('express');
const expL = require('express-ejs-layouts');
const app = express(); //Create a Web Application
//EJS
app.use(expL);
app.set('view engine', 'ejs')
//Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
app.listen(3000, ()=> console.log('Listening at 3000'));
app.use(express.static('public'))
index.js
const express = require('express');
const router = express.Router();
router.get('/',(req, res) => {
res.render('mainPage',{title: 'Groupy'}); (THIS ONE WORK AND READ THE CSS)
});
module.exports = router;
users.js
const express = require('express');
const router = express.Router();
//Login Page
router.get('/login',function(req, res) {
res.render('login',{title: 'Groupy Login'}); (DON'T READ CSS)
});
//Register Page
router.get('/register',function(req, res) {
res.render('register',{title: 'Groupy Register'}); (DON'T READ CSS)
});
module.exports = router;
layout.ejs
<html>
<head>
<script type="text/javascript" src="code.js"></script>
<link rel="stylesheet" type="text/css" href="./css/style.css">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</script>
<title><%= title %></title>
</head>
<body>
<div id="particles-js"> </div>
<script src="js/particles.min.js"></script>
<script src="js/app.js"></script>
<h2>teste</h2>
<%- body %>
</body>
mainPage.ejs
<h1 id="title">Groupy</h1>
<div id="firstBox">
<div id="SignIn">Register <div id="login">Login</div>
</div>
</div>
<br>
<div id="mainBox"></div>
login.ejs
<h1 id="title">Groupy Login</h1>
Reseult of login (without CSS):
teste
Groupy Login
Can you try the following app.use instead of app.use(express.static('public'))
app.use('/public', express.static(path.join(__dirname, 'public')));
Also you should import path module
const path = require('path');
The error was the path of css and javascript (particles.js)
<link rel="stylesheet" type="text/css" href="/css/style.css">
<script src="/js/particles.min.js"></script>
<script src="/js/app.js"></script>

node js res.render does not work, but res.send does

I am setting up the environment for a node js app. But the views/ejs files are not being rendered.
If i do:
app.get("/", function(req, res){
res.send('Hello');
});
it works.
But if i do:
app.get("/", function(req, res){
res.render("welcome");
});
it doesn't.
my app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const indexRoutes = require("./routes/index");
const userRoutes = require("./routes/user");
const ejsLayouts = require("express-ejs-layouts");
const path = require("path");
mongoose.connect("mongodb://localhost/userAuth", function(err, res) {
if (err) throw err;
console.log("Connected to database");
});
//EJS
app.set('view engine','ejs');
app.use(ejsLayouts);
app.use(express.static(__dirname + '/public'));
app.set('views',path.join(__dirname+'/views'))
//ROUTES
app.use("/", indexRoutes);
app.use("/user", userRoutes);
app.listen(3000, function() {
console.log("server started");
});
my index.js file (userLogin/routes/index.js)
const express=require("express");
path = require('path');
router= express.Router();
router.get("/",function(req,res){
res.render("welcome");
});
module.exports = router;
my folder structure
userLogin
/..
/routes
/index.js
/views
/welcome.ejs
I have an h1 element olny in welcome.ejs file.
Looking at the code you provided, in index.js you are trying to render a view called check, when the only view you have is called welcome. Your paths and routes look to be correct, rendering the correct view should work.
app.engine('html', require('ejs').renderFile);
if u woudlike to render .html files
then
fs.readFile(path.resolve(__dirname + '/../public/views/logs.html'), 'utf-8', (err, content) => {
let renderedHtml = ejs.render(content, {'user': req.session.db}); //get redered HTML code
res.end(renderedHtml);
})
you should have views/layouts/layout.ejs file if you are using express-ejs-layouts npm
inside app.js :
const ejs =require('ejs');
const ejsLayouts = require("express-ejs-layouts");
app.set('view engine','ejs');
app.use(ejsLayouts);
app.set('layout', 'layouts/layout');
layout.ejs file has common layout that follow all files
if you are using bootstrap then your layout.ejs file would be like :
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<title></title>
</head>
<body>
<?- body ?>
</body>
</html>
so now other ejs pages will only have content to display
like welcome.ejs file is
<h1>Welcome Page</h1>

CSS seems to be sent to page, but nothing applies [ExpressJS + Handlebars]

I am attempting to do a very simple page with Handlebars and Express with NodeJS, however I am running into difficulty getting it to display css. It seems that the browser is receiving the CSS file given the feedback and the 200 code I'm getting in my Node window, but no effect is shown on the actual page.
file structure
app.js
/public
/stylesheets
style.css
/views
/layouts
main.handlebars
home.handlebars
app.js
var express = require('express');
var exphbs = require('express-handlebars');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', express.static(path.join(__dirname, '/public')));
var person = {
name:"Clay",
age:"20",
attr:["tall","handsome","wearing a red sweater"]
}
app.get('/', function (req, res, next) {
res.render('home', {layout: false, people: person});
});
module.exports = app;
main.handlebars
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Database</title>
<link rel="stylesheet" href="stylesheets/style.css" />
</head>
<body>
{{{body}}}
</body>
</html>
home.handlebars
<h1>Example App: Home</h1>
hello world
style.css
body {
background-color: red;
}
node console

Categories

Resources