Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
Dail Avatar asked Dec 22 '11 22:12

Dail


People also ask

How do you show variables in EJS?

It is possible to access JS variable in . ejs file. You just need to pass the JS object as second parameter of res. render() method.


1 Answers

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.

like image 163
Adam Avatar answered Oct 19 '22 04:10

Adam