Mankind1023
Mankind1023

Reputation: 7752

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.

Upvotes: 10

Views: 32797

Answers (9)

romualdo gino
romualdo gino

Reputation: 1

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 )

Upvotes: 0

redolF
redolF

Reputation: 61

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

Upvotes: 1

Shubham Gupta
Shubham Gupta

Reputation: 434

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.

Upvotes: 11

Eniola Ademola
Eniola Ademola

Reputation: 76

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

Upvotes: 0

Daniel Lukudu
Daniel Lukudu

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

Upvotes: -1

Vimal kumar
Vimal kumar

Reputation: 39

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

Upvotes: 2

Joseph Flores
Joseph Flores

Reputation: 21

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

Upvotes: 1

Praveen Patel
Praveen Patel

Reputation: 1309

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.

Upvotes: 4

lamnv60533
lamnv60533

Reputation: 69

This worked perfectly

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

Upvotes: 6

Related Questions