How to load a javascript file only in some ejs templates? - node.js

I am building an app with the help of node, express and ejs. The structure of my app is in this way that I used a footer.ejs file in all pages (templates) and in that file I have a code like this:
footer.ejs
<!-- bootstrap js CDN -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<!-- some other codes -->
</div>
</body>
</html>
But in some of my pages I need some js codes. Because I don't want to load them in un-related pages, I decided to add the <script> tags of them individually on that page only like the code below:
information.ejs:
<!-- the html tags of this page (called information.ejs) are here -->
<!-- ... -->
<!-- end of html tags -->
<script src="/javascripts/upload.js"></script> <!-- this is the script codes that only need in this page -->
<%- include('include/footer') %>
That works fine. But now I need some functionality of bootstrap.js in my upload.js script. The problem here is that upload.js is loaded before the bootstrap.js and I could not use the functionality of bootstrap in my script.
To solve that problem I decided to define a variable called infoId and send that to information.ejs like below in my express router file:
router.get('/dashboard2/:infoId', (req, res) => {
res.render("information", {
infoId: req.params.infoId,
});
})
And then deleted the script tag from the end of information.ejs file and added it in footer.ejs like below:
new footer.ejs:
<!-- bootstrap js CDN -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<!-- added new -->
<% if(infoId !== undefined) { %>
<% if(infoId == "information") { %>
<script src="/javascripts/upload.js"></script>
<% } %>
<% } %>
<!-- some other codes -->
</div>
</body>
</html>
In this case I get the error of variable infoId is undefined when I navigate to other routes (pages). Could I fix this problem without sending the infoId variable to all other routes?

Related

SweetAlert2 is not working in node.js

I'm making website for db study.
I wanted to alert to user if user didn't input id and password in register page.
So I installed sweetalert2 by npm. But sweetalert2 doesn't work in route.js which connect user's ask and server.
var swal = require('sweetalert2');
router.post('/register', function(req, res){
if(!req.body.id && !req.body.password){
swal('WARNING','You must input both id and password!','error')
}
else{
swal('COMPLETE','You registered your information!','success');
res.redirect('/');
}
})
How can I fix it?
I used .ejs file to use sweetalert2.
<!DOCTYPE html>
<html>
<head>
<% include ../pages/head %>
</head>
<body>
<% if(fail) { %>
<% include ../partials/alert_login %>
<% } %>
<% include ../pages/login %>
</body>
</html>
in login_connect.ejs includes when user fail login alert_login.ejs file and alert_login.ejs includes script tag of using swal of sweetalert2 module.
But It isn't work. What is the problem?
alert_login.ejs is below.
<script type="text/javascript">
alert("You are not our member!");
</script>

ejs include on click

I'm trying to create a dynamically included in an ejs page (using <%- include('partials/content') %>) on my node.js project.
Is there a way I can create a variable for the to-be-included page and change it on a button click?
Let's assume your partials/content file includes content like:
<h1>Lorem ipsum dolor sit amet</h1>
A file named partials/content2:
<h1>consectetur adipiscing elit<h1>
Your main template file would wrap the partials content by a <div> with the id result and include a script file where you select this <div> by using var $result = $('#result'); so you have it in a variable. Then you can register a click handler on your button. On click you request the wished template file and replace the content.
Main template:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="result">
<%- include partials/content.ejs %>
</div>
<button id="change">change</button>
<script>
var $result = $('#result');
$('#change').click(function() {
$result.load('/content2');
});
</script>
</body>
</html>
Then you need a controller on the backend like:
app.get('/content2', function (req, res) {
res.render('partials/content2');
});

Node Express EJS Dynamic template render

Hi I am trying to create dynamic template system in express, where I will get dynamic content from database and then render output in single index.ejs file.
Here is my index.js
router.get('/', function(req, res, next) {
var dataFrmDB = {
pageContent: "<%= data.pageTitle %>",
pageTitle: "home"
};
res.render('index', {data:dataFrmDB} );
});
And index.ejs contains:
<%= data.pageContent %>
What I should do so that I can render "home" as output. Is this possible?
I was working on something similar when we migrated from drupal to nodejs, I used ect for rendering instead of jade, its faster and much easier to deal with, However, its much better to use design pattern if you have a big dynamic website
js controller file
model.homepage(function(data)
{
res.render("homepage.ect",data,function(err,html)
{
// Do something before you send the response such as minification, or error handling
res.send(html);
});
});
ECT file
<html xmlns="http://www.w3.org/1999/xhtml" lang="ar" xml:lang="ar">
<head>
<%- #page.title.body %>
<%- #page.headerScript.body %>
<style type="text/css">#homepage-container{min-height:300px;color:#353535;float:right;width:100%}</style>
</head>
<body>
<% include 'upper_bar.ect' %>
<%- #page.headerAd.ads %>
<%- #page.notifications.body %>
<%- #page.autocomplete.body %>
<%- #page.redirect.body %>
<%- #page.navigation.body %>
<%- #page.overlayAd.ads %>
</body>
</html>
why bother so much?
You can easily do this using templatesjs
without any template engine.
let me show you how your work can be done using templatesjs
html file
<html>
<head>
<title> <%title%> </title>
</head>
<body>
your content goes here
</body>
</html>
now use templatesjs in you node.js file
var tjs = require("templatsjs");
router.get('/', function(req, res, next) {
var data = fs.readFileSync("./index.html");
tjs.set(data); // invoke templatesjs
var output = tjs.render("title","home");
/* this will replace the <%title%> tag
in the html page with actual title*/
res.write(output);
res.end()
});
i have used fs.readFileSync to keep simplicity of code you can use the asynchronus function if you want (fs.readFile).
a good referrence can be found here
Installation :
$ npm install templatesjs

Access localStorage from ejs template

I am trying to save some data sent by the server to an EJS template in localStorage on the client side. However, when I try to access localStorage in the template, I get localStorage is undefined.
Here is a part of my page.ejs:
<% localStorage.setItem('info', JSON.stringify({'user': user})) %>
where user is a value received from the server.
Is this possible?
There are a few options depending on what you want to do. I came across this post looking to do something a little different but here is one way:
After the template renders and passes the data user, add a script tag to modify localStorage.
<!-- example.ejs -->
<!-- check for user on page load -->
<% if (typeof user != "undefined") { %>
<!-- make user available to script tag -->
<% var user = user %>
<!-- use script tag to access ejs data and local storage -->
<script>
let user = <%- JSON.stringify(user) %>;
localStorage.setItem('info', JSON.stringify({'user': user}));
</script>
<% } %>
check this once its worked for me,
<script>
let data =JSON.parse('<%- JSON.stringify(data) %>')
localStorage.setItem("data", JSON.stringify(data))
</script>
and for accessing,
<script>
let data = JSON.parse(localStorage.getItem("data"))
</script>

Script stops at YAHOO.util.Event.addListener

I am new to YUI. Just trying to get a most basic functioning example working on my site.
Here is the code:
<button id="mytest">test</button>
<script type="text/javascript">
var helloWorld = function(e) {
alert("Hello World!");
}
</script>
<script type="text/javascript">
alert('xx');
YAHOO.util.Event.addListener("mytest", "click", helloWorld);
alert('x2');
</script>
The xx alert shows, but the x2 alert never does. And, clicking on the button does not fire the HelloWorld function.
I have the necessary include files:
<!-- Required CSS -->
<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.8.1/build/progressbar/assets/skins/sam/progressbar.css">
<!-- Dependency source file -->
<script src = "http://yui.yahooapis.com/2.8.1/build/yahoo-dom-event/yahoo-dom.event.js" ></script>
<script src = "http://yui.yahooapis.com/2.8.1/build/element/element-min.js" ></script>
<!-- Optional dependency source file -->
<script src="http://yui.yahooapis.com/2.8.1/build/animation/animation-min.js" type="text/javascript"></script>
<!-- ProgressBar source file -->
<script src = "http://yui.yahooapis.com/2.8.1/build/progressbar/progressbar-min.js" ></script>
you should be sure the js files are included on you html files,the code your write is write!
Believe I found it. Or at least I was able to find other examples which worked. But in my case I believe the problem is the js files I was referencing in fact did not exist. Namely this file:
http://yui.yahooapis.com/2.8.1/build/yahoo-dom-event/yahoo-dom.event.js
sure, it is yahoo dash dom DASH event, not yahoo dash dom DOT event

Resources