How to print a variable directly using EJS template engine? - node.js

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

Related

how to use in_array in ejs template

How to use in_array or similar in inside an ejs template?
This is how I use it on php:
<?php
$cur_repository_id = array();
foreach($dbrepos as $row){
$shared_ids = $row['shared_ids'];
if(in_array($user_id, $shared_ids)){
$selected = "selected";
$cur_repository_id[] = $row['rep_id'];
}else{
$selected = "";
}
?>
<option value="<?php echo $row['rep_id'];?>" <?php echo $selected;?>><?php echo $row['namespace'];?></option>
<?php
}
?>
Equivalent of in_array in javascript is includes
So if for example you want to pass an array from Node.js to ejs file, you can do something like that:
res.render('index', {numbers : [1, 23, 44]});
And then inside ejs you can use the method includes, for example:
<body>
<% if(numbers.includes(44)){ %>
<h1>44 exists</h1>
<% } else{ %>
<h1>44 not exists</h1>
<% } %>
</body>
Also you can use method indexOf, which return the index of given value in an array.

EJS: Pass array of pages into include(page)

I've created a dashboard page where a user can save different components of the site to one page for quick viewing. I'm able to dynamically load one component as follows:
index.js
res.render('dashboard',{comp: 'component1'});
dashboard.ejs
<%- include(comp) %>
but I would like to do something like this:
index.js
res.render('dashboard',{comp: ['component1', 'component3']});
And have the ejs page loop through the include(), this way i can show 0 to n components on the dashboard page.
I've tried wrapping the include in a for loop like so:
<%- for(c in comp){include(c)} %>
but ejs did not like this.
Am I going about this the wrong way?
Try this
<% for(var i=0; i < comp.length; ++i) { %>
<%- include(comp[i]) %>
<% } %>
in your code, c is the index not value, comp[c] is your component.
<% for(c in comp){ %>
<%- include(comp[c]) %>
<% } %>

How to place an EJS tag within another

I am using EJS as my templating engine. I am passing variables from node js to ejs like...
router.get("/AdminDatabase", function(req, res) {
res.render('Pages/AdminDatabase', {title: 'WebFormsAdmin', role: 'System Admin' });
});
I am building a role base control and for this I want to change the header of the page base on the role of user.
<% include ../partials/Common/header_<%= role %> %>
The problem is with the above segment. How can I place the variable role inside this EJS code segment?
My header files are
header_System Admin.ejs,
header_Survey Admin.ejs,
header_Survey Taker.ejs
A workaround would be to do a conditional render like so:
<% switch (role) {
case 'System Admin': %>
<% include ./partials/header_System_Admin %>
<% break; %>
<% case 'Survey Admin': %>
<% include ./partials/header_Survey_Admin %>
<% break; %>
<% default: %>
<% include ./partials/header_Survey_Taker %>
<% break; %>
<% } %>
Note that the first case must be grouped with the switch declaration. Make sure the paths are correct for your partials.
You can concatenate the path and the variable.
<%- include('../partials/Common/header_'+role) %>

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

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

Resources