Undefined variable in ejs template with express - node.js

I am using ejs template engine in my express app with conditional rendering in title tag
//layout.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= pageTitle ? pageTitle : ''%></title>
</head>
<body class="container p-3 border">
<%- include('../partial/header.ejs') %>
<main><%- body %></main>
</body>
</html>
// header.ejs
<nav class="d-flex justify-content-between border p-2">
<ul class="nav">
<% if (user.isAuthenticated) { %>
<li class="nav-item mx-2 my-auto">
home
</li>
</ul>
</nav>
When I am sending response like this
res.render('upload',{pageTitle:'upload video'}
I do not know why the result will be pageTitle is not defined while pageTitle is rendering conditionally.

Related

EJS not able to render page due to class declaration

<header class="main-header">
<nav class="main-header__nav">
<ul class="main-header__item-list">
<li class="main-header__item"><a class="<%= path === '/' ? 'active' : '' %>" href="/">Shop</a></li>
<li class="main-header__item"><a class="<%= path === '/admin/add-product' ? 'active' : '' %>" href="/admin/add-product">Add Product</a></li>
</ul>
</nav>
When I try to render the page in my node js application I am getting an error. Saying there is an error
I am not so used to writing ejs but when I remove the class="<%= path === '/' ? 'active' : '' %>" in the navigation.ejs it seems to work
Error Image
Use <%- include('RELATIVE/PATH/TO/FILE'); %> to embed an EJS partial in another file.
The hyphen <%- instead of just <% tells EJS to render raw HTML.
The path to the partial is relative to the current file.
and also use ; at end of include
Here is an example...
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('../partials/head'); %>
</head>
<body class="container">
<header>
<%- include('../partials/header'); %>
</header>
<main>
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
</div>
</main>
<footer>
<%- include('../partials/footer'); %>
</footer>
</body>
</html>

How to check in layout if user is logged in

Like in title.
I have layout:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link
rel="stylesheet"
href="https://bootswatch.com/4/journal/bootstrap.min.css"
/>
<title>Node.js & Passport Login App</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor03" aria-controls="navbarColor03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor03">
<ul class="navbar-nav mr-auto">
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Szukaj!</button>
</form>
<li class="nav-item active">
<a class="nav-link" href="/index">Strona Główna
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">O nas</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<%if (!isLoggedIn) { %>
<div> <a class="nav-link" href="/users/logout">Wyloguj</a></div>
<% } %>
<%if (isLoggedIn) { %>
<div> <a class="nav-link" href="/users/login">Zaloguj</a></div>
<% } %>
</li>
</ul>
</div>
</nav>
<div class="container"><%- body %></div>
<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.6/umd/popper.min.js"
integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"
integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
crossorigin="anonymous"
></script>
</body>
</html>
and some routes like e.g register view,where I check if user isLogged(no way to registration) etc.
router.get('/register', (req, res) =>
res.render('register',{isLoggedIn:isLoggedIn()}));
I have 2 problems:
1)<%if> in my layout doesn't work (i don't know why)
2)How to inject state of user (logged or not) to layout? I don't want to repeat all of the code from layout on my views.
I think you have swapped the login/logout elements. For !isLoggedIn should be Zaloguj, for isLoggedIn should be Wyloguj.
Generally, I attach to render some (not all, as it can contain pasword hashes) user data res.render(‘register’, { user }) You will need them either, you will want to display logged in user name or so.
Then:
<% if (user) { %>
<h2><%= user.name %></h2>
<% } %>
If you have a part of ejs you want to have in other templates, just use includes:
<div id=“parent_div”>
<div id=“register_div”>
<% include('register.ejs') %>
</div>
<div id=“mainbody_div”>
<% include('body.ejs') %>
</div>
<div>
I solved my problem - thanks to #Fide for show me a way where is a bug!
router.get('/register',
function (req,res){
res.render('register', {user: req.User} )
});
I have to take User from req - simple but I spent a lot of time on it!

Nested URLs not working with requirejs

Using requirejs, I can use simple routes like /register, but I always get an error when I try a nested route like /register/1 or something.
This works (where the route is just /register):
layout.js
define(['require', 'axios'], (require, axios) => {
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<h3>My App</h3>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation">Login</li>
<li role="presentation">Register</li>
</ul>
</nav>
</div>
</div>
</div>
`;
if (window.location.pathname === '/') {
window.location.pathname = '/home'
}
axios.defaults.headers.common['authorization'] = Cookies.get('token')
return layout
})
register.js
define(['layout'], layout => {
if (window.location.pathname === '/register') {
console.log("Got it") // This works since the route is just '/register'
}
})
This does not work (where the route is /register/1):
layout.js
define(['require', 'axios'], (require, axios) => {
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<h3>My App</h3>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation">Login</li>
<li role="presentation">Register</li>
</ul>
</nav>
</div>
</div>
</div>
`;
if (window.location.pathname === '/') {
window.location.pathname = '/home'
}
axios.defaults.headers.common['authorization'] = Cookies.get('token')
return layout
})
register.js
define(['layout'], layout => {
if (window.location.pathname === '/register/1') {
console.log("Got it") // Error
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link
rel="stylesheet"
type="text/css"
href="/stylesheets/style.css">
<link
rel="stylesheet"
type="text/css"
href="/stylesheets/registration.css">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<script
type="text/javascript"
src="/javascripts/styles/js.cookie.js">
</script>
<script data-main="config" src="require.js"></script>
<script>require(['config'])</script>
</head>
<body>
<div id="my-app"></div>
</body>
</html>
config.js
requirejs.config({
baseUrl: 'javascripts/views',
paths: {
allConversations: 'allConversations',
conversation: 'conversation',
home: 'home',
layout: 'layout',
loginView: 'login',
login: '../scripts/login',
logoutHandler: '../scripts/logout',
memberProfile: 'memberProfile',
profile: 'profile',
register: 'register',
conversationCount: 'conversationCount',
nav: 'nav',
axios: '//unpkg.com/axios/dist/axios.min',
jquery: [
'//code.jquery.com/jquery-3.3.1.min',
'//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min'
],
bootstrap: ['//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min'],
fontAwesome: ['//use.fontawesome.com/7973784de3'],
},
})
require([
'home',
'layout',
'loginView',
'login',
'logoutHandler',
'nav',
'register'
])
How do I use nested URL routes with requirejs?
First problem. You are loading config module twice. data-main attribute specifies what modules should be loaded after the RequireJS load. So the second line is basically a duplicate of this
<script data-main="config" src="require.js"></script>
<script>require(['config'])</script>
Please replace this with just
<script data-main="config" src="require.js"></script>
Second problem, you have syntax error in layout.js. Your syntax looks like JSX, not regular JavaScript. Please amend this or use RequireJS JSX files loader plugin -> https://github.com/philix/jsx-requirejs-plugin
Can you please show use you config module?
Cheers.

EJS pages with parameters and partials hang

I have a weird problem happening on my ejs pages. When I include header and footer partials on any page that loads with a route parameter, the page hangs. When I hit the stop button on the page load, the page loads fine. On pages that do not have a route parameter, I have no issues.
I get the following error in node (the page loads with a route parameter called eventid):
params for results to find by eventid: { eventid: 'app.css' }
SOMETHING WENT WRONG GETTING RESULT: { CastError: Cast to ObjectId
failed for value "app.css" at path "event_id" for model "results"
I added a comment below after posting this question. I figure I would add some information here to give more details. My app.css link in the header partial is the cause of my problems. When I comment it out it works fine. In node, I've used the following line to include files in my resources folder which is in the root of my app. This works fine except when i load it using the partials footer. app.use(express.static(path.join(__dirname, 'resources')))
Sample pages...
<% include ../partials/header %>
<h3>Sample page</h3>
<% include ../partials/footer %>
Header partial...
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<nav class="navbar navbar-inverse navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="google.com"><i class="fa fa-futbol-o"></i> PESers Only</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>Link 1</li>
<li>Link 2</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Register</li>
<li>Log In</li>
<li>Log Out</li>
</ul>
</div>
</div>
</nav>
<!-- <div id="wrapper"> -->
<div class="container">
Footer Partial...
</div> <!-- close container -->
<!-- </div> close wrapper -->
</body>
<footer class="footer">
<div class="footer-content list-inline">
Footer text | Contact Us
</div>
</footer>
</html>
It turns out that the problem I was having was related to the referencing of external files (in this case my app.css file). I was referencing it in my ejs header partial using: <link rel="stylesheet" type="text/css" href="app.css"> however the error was fixed when I added a backslash to the href: <link rel="stylesheet" type="text/css" href="/app.css">.
Essentially, when referencing resources such as a css file that is in a folder that is declared in app.use (app.use(express.static(__dirname + "/resources"));) you need the backslash to reference the root of your application and then access the resource you plan to reference in the ejs views.

Update/Modify variable in ejs page

I have a ejs page using node where I want to update my variable. The problem is that it is a part of a multipage view.
I'm passing a user variable from the node server to the webpage.
Once on the page, I have a header. I show the name in the header, but in the body, I update the data.
<!DOCTYPE html>
<html ng-app="KBase" ng-init= "m_user=<%=JSON.stringify(user)%>">
<head>
<title>Index</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body ng-controller="accountController">
<header>
<% include header %>
</header>
<div class="container" ng-controller="accountController as up" ng-init="up.m_user = m_user">
I'm using angular to update the data. It is going to the server and updating. However, would rather not update the entire page and I don't want to hae multiple headers. However, the multiple headers is the only way I can see fixing the issue.
My header.ejs
<% if (user){ %>
<ul class="nav navbar-nav navbar-right" >
<!--<li>Link</li> -->
<li class="dropdown">
<%=(user.displayName)%><span class="caret"></span>
<ul class="dropdown-menu">
<li>logout</li>
<li>account settings</li>
<!-- <li>Something else here</li>
<li role="separator" class="divider"></li>
<li>Separated link</li> --!>
</ul>
</li>
</ul>

Resources