How to print a variable directly using EJS template engine? How to print a variable directly using EJS template engine? express express

How to print a variable directly using EJS template engine?


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.