How to print a variable directly using EJS template engine?

Dail picture Dail · Dec 22, 2011 · Viewed 21.2k times · Source

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?

Answer

Adam picture Adam · Dec 22, 2011

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.