How to print a variable directly using EJS template engine?
Asked Answered
L

4

29

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?

Lungi answered 22/12, 2011 at 22:22 Comment(2)
Why wouldn't you just use <%= value %>?Honky
because I, for example, would like to do something like <% if (value) { PRINT "foobar" } %>, if this condition is met, check a checkbox or something similar.Hyacinthe
G
25

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.

Gangling answered 22/12, 2011 at 22:43 Comment(2)
Or even shorter <%= value || '' %>Tm
its simply <%=' '%> you can either put your key and it will print the key's value or you can put a string in quotes and it'll print that.Deafen
A
0

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.

Attestation answered 5/12, 2020 at 16:55 Comment(0)
U
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

Unclothe answered 17/7, 2022 at 1:46 Comment(0)
P
0

after some struggle I found this,

<% if(userData.email != null){ 
   __append('email found!'); 
   or
   __append(userData.email);
}%>

it is working fine in my nodejs express ejs app

Pierpont answered 23/1 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.