Use console.log in EJS
Asked Answered
D

9

10

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.

Demers answered 20/11, 2016 at 23:19 Comment(0)
L
11

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.

Laural answered 7/10, 2018 at 5:8 Comment(0)
B
6

This worked perfectly

<% console.log('heheeh', JSON.stringify(doc, null, '\t')) %>

Bacchus answered 22/11, 2016 at 7:23 Comment(1)
What do you mean here?Admiration
G
4

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.

Gilberte answered 4/4, 2020 at 6:16 Comment(0)
M
2

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

Macao answered 5/3, 2021 at 3:8 Comment(0)
L
1

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); %>
Labial answered 24/9, 2022 at 16:17 Comment(0)
C
0

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

Cardiomegaly answered 10/4, 2020 at 21:6 Comment(0)
H
0

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

Hydroxy answered 17/7, 2022 at 2:2 Comment(0)
L
0

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 )
Lsd answered 14/1, 2023 at 10:38 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Supermundane
S
-1

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

Supremacy answered 23/4, 2021 at 0:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.