Render EJS partial on client side - Could not find the include file error - node.js

I am trying to update with socket.io a data which is coming for some partials.
I have a partial called info_card.ejs in partials package and it has two params: title and info. I have tried rendering the following code:
<% info_cards.forEach(function(card) { %>
<%- include("../partials/info_card", card) %>
<% }); %>
The first render is made by the server, and when I am trying to render in the client side (inside a js script) as following:
const update_info_cards =
[
{title: "title1", info: "info1"},
{title: "title1", info: "info2"}
]
var html = ejs.render(`<% info_cards.forEach(function(card) { %>
<%- include("../partials/info_card", card) %>
<% }); %>`, {info_card: update_info_cards })
I get this error:
1| <% info_cards.forEach(function(card) { %>
>> 2| <%- include("../partials/info_card", card) %>
3| <% }); %>
Could not find the include file "../partials/info_card"
Don't know how to fix it, I have tried to change the path for such a long time, but still get this error. I have also tried to look up for some answers on the internet - couldn't find any.
I saw that I can't do include on client side, so what's the alternative, because I really can't see me coping all the html code of the card multiple times?
Thanks!

Related

How do i make the ejs variable work that i send from nodejs?

I am tring to get a variable that i send from nodejs to ejs to work. But for some reason it wont, i cant figure out why.
This is the index.js:
var newOne = "Yes"
router.get('/main', ensureAuthenticated, (req, res) =>
res.render('main', {
user: req.user,
newOneInView : newOne
})
)
And this is in the main.ejs file:
<%if (newOneInView == "Yes") { %>
document.getElementById("avatar").src = "/static/images/Apocaliptic1.png";
<% } %>
So what i am trying to achieve is that variable will be seen from the nodejs at the main.ejs page but some reason it wont change the image SRC. What am i doing wrong here?
In your template you need to make sure that you place the code for changing the src attribute in a script that is placed after the element (alternatively you can use a listener for the content to be loaded), e.g:
<body>
<img id="avatar" src="/some-other-path"/>
<script>
<% if (newOneInView === "Yes") { %>
document.getElementById("avatar").src = "/static/images/Apocaliptic1.png";
<% } %>
</script>
</body>

How to edit the render information with if else in ejs file

Hi i am trying to add condition for the render value in ejs file. i want to do something if value is equal to blah blah. I tried as shown below.
<% if (user) { %>
<div class="user_info">
<div>
<p>User Name<%= user.username %></p>
<p>User bio<%= user.user_bio %></p>
//here i want to put if else statement
//like this
<% if (user.user_age = null){ %>
<p>Your age is not defined. </p>
<% } %>
<% else if (user.user_age = 10){ %>
<p>You are a <%= user.user_age %> old tween!! </p>
<% } %>
<% else { %>
<p>You are a <%= user.user_age %> old Adult!! </p>
<% } %>
</div>
</div>
<% } else { %>
<p>No User!</p>
<% } %>
Clearly this if else statement i tried is not working.
How can i do this?
I have worked on this type of project something like that of whatsapp web,
its going to be a little hard because there are not many good tutorials out there, but I can give you some tips or steps you need to follow, to give the code would be very lengthy and its propriety code that I've worked on so I cant share that.
First of all to connect to server using a mobile or qr scanner you have to have a private or seperate socket to connect to the server. For that you can have to use web sockets which is a big task but you can use a simple socket library socket.io its fairly easy.
You will have to create a unique socket and key which you need to pass through the r itself(you have to render the qr code image through node js with the key as value) for that you can use 'qrcode' npm package.
For now your task here is done.
The difficult part starts here. You have to make an android/ios app to use that data which will use it in its own way, for ex in whatsapp when you can qr code from app it logs you in to your account and load contacts, messages, etc on the screen.
Im not an android or app developer for now, that part has to solved by you.

Express/EJS - if it's a specific view file thats rendered do something

I have a view that is:
/views/signup.html
I want to have different elements on the page in my main layout template depending on what view is loading.
In my main layout file, when that specific view is rendered I want to do something like:
<% if (ecomHeader) { %>
<% include includes/signup-nav.html %>
<% } %>
<% else { %>
<% include includes/nav.html %>
<% } %>
This obviously doesn't work
ReferenceError: ../views/layout.html:9
7| </head>
8| <body>
>> 9| <% if (ecomHeader) { %>
10| <% include includes/signup-nav.html %>
11| <% } else { %>
12| <% include includes/nav.html %>
Can you do that? is that how that works?
render code:
...
let token = createCSRFToken(req);
let ecomHeader = true;
res.render('premium/signup', {
message: req.flash('signupMessage'),
token: token,
ecomHeader: true
});
...
There is a exports. thing that wraps this, not sure if thats relevant or not
You're else condition is missing certain things. Make sure you pass signup: true/false boolean from the back-end to your views.
res.render("main-template", {
signup: true/false
});
Then in your html, you need to do this - Make sure you use <%-.
<% if(signup){ %>
<%- include('includes/signup-nav.html'); %>
<% } else { %>
<%- include('includes/nav.html'); %>
<% } %>

Use console.log in EJS

Is it possible to use console.log in a node / ejs template? It doesn't seem to do anything when I try, even something as simple as:
<% console.log('test') %>
I've also tried:
<%= console.log('test') %>
Nothing shows up in the console.
I think you are expecting it to show in the developer console. It will not show up there.
console.log() in EJS file will show the log in the terminal where the server is running.
This worked perfectly
<% console.log('heheeh', JSON.stringify(doc, null, '\t')) %>
console.log() is working fine, but its log does not display in dev tools.
So, check your terminal first:
<% console.log("test") %>
It's perfect.
console.log(test) in ejs file will show the log in the terminal
And if you want to see test object or value in browser than try
<%= test %>
This will show objects as string
I know this is a really old thread, but I just had this issue and this is what I ended up doing:
<% var data = JSON.stringify(htmlWebpackPlugin) %>
<script>
console.log(<%= data %>)
</script>
It doesn't look pretty, but it works
Code
Output
<% console.log(posts) %>
NB: Make sure you define your variable in any other file you have eg app.js file...
let posts = [];
app.get("/", (req, res) => {
res.render("home", {
posts: posts
});
});
OUTPUT
Click me
first, Your home route inside your index.js/server.js/app.js, render a variable you want console log in another ejs file; in the code below, nposts is a variable or an array;
app.get("/",function(req,res){
res.render("home", {posts: nposts});
then in your ejs file, in this example in the home.ejs console.log in the <% %> tags
<% console.log(posts); %>
send from serve-side
let item = [arr1, arr2, arr3]
res.send("index", { item })
in client-side
example
use in script
console.log('<%- item %'>
arr1,arr2,arr3
console.log('<%- JSON.stringify( item ) '%>
["arr1","arr2","arr3"] //text
var newArray = JSON.parse('<%- JSON.stringify( item )%>')
console.log(newArray )
<% { %>
<script>console.log('hello')</script>
<% } %>
this code is work well.
create { } by <% %> from ejs.
We can add javascript code inside { }.
The simple answer would be:
If you are in your home route and you want to test any condition you would have to use ejs tags. inside the tags drop your normal console.log.
<% console.log(test) %>

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

Resources