Use console.log in EJS - node.js

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

Related

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

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!

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>

Unable to display flash message in view with ejs template

I am a newbie in NodeJS. I have a problem that I am unable to show flash message in my view.
Here is my Controller,
index : function(req, res){
res.locals.flash = _.clone(req.session.flash);
res.locals.layout = false;
res.view('login');
},
login : function(req, res){
....
if(!admin){
req.session.flash = {
err : 'User is not found.' // My flash message
}
res.locals.layout = false;
res.redirect('login');
return;
}
.....
}
Here is my view,
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
<% JSON.stringify(flash.err) %>
</div>
<% } %>
When login is false, it show only an empty alert box.
And I have a second problem. When I refresh page, The alert box isn't disappeared.
Could someone help me please.
Thanks a lot.
The alert box keeps on appearing because the req.session.flash object persists the session, so you need to null that out once it's used, or you can just simply use req.flash(), which does that for you. So change your index method to something like this:
index: function(req, res) {
// req.flash() returns the contents of req.session.flash and flushes it
// so it doesn't appear on next page load. No need to clone.
res.locals.flash = req.flash();
res.locals.layout = false;
res.view('login');
},
Now, onto the second problem. The error messages aren't appearing because you aren't using the proper EJS syntax to output escaped values into the view. All you need to do is change your code to this:
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
// Change <% to <%=
<%= flash.err %>
</div>
<% } %>
No need to JSON.stringify, unless you like the quotes. Notice that I changed the <% to <%=, which in EJS means "escape this and output it". It's not template HTML or anything like that, so it's okay to escape it anyway.

Underscore Js _.each used with ejs error

I am trying to display the value in array using _.each and EJS dynamically. I am getting the values when i do it manually,but getting Unexpected token ; error while using _.each loop.
Here is the code
`<% _.each(pro,function(prof) { %>
alert(prof.Name);
<% } %>`
pro = {[object Object],[object Object]}
when i do it manually,i get the output.
i.e.
`<%= pro[0].Name %>`
Need help! Any other suggestions? Thanks
You seem have missed a parentheses here:
<% }) %>`
Beyond that, I'm not sure you can use underscore inside your EJS templates.
Try using a regular for.
<% for(var i=0; i<prof.length; i++) {%>
<li><%= prof[i] %></li>
<% } %>

How to print a variable directly using EJS template engine?

I'm using Node.js with Express web framework (and EJS template engine).
When I have to print a variable I do something like:
<% if (value) { %>
<%= value %>
<% } %>
Can I do the same thing without open others brackets ? Like:
<% if (value) { PRINT VALUE } %>
Is this possible? How to print the variable?
I'm amazed to find that apparrently you can't do it, like in PHP:
<?php if ($value) : ?>
<?php echo $value; ?>
<?php endif; ?>
However a slightly better solution may be to do
<%= (value) ? value : '' %>
I say this assuming that the condition may occasionally be more complex, i.e.
<%= (str.length > 100) ? truncate(str) : str; %>
Which is much nicer than
<% if (str.length > 100) { %>
<%= truncate(str) %>
<% } %>
even if it is a slightly contrived example.
I'd love to be shown a direct command to do it, as per your original question.
There is now an outputFunctionName parameter that you can use. According to the documentation:
outputFunctionName Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags.
<% 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
});
});

Resources