Can I run javascript in EJS tags?

Hey everyone, imagine I have a database with the Unix time stored in it (something like 1599194185442). I pass this to a EJS file and show the Unix time like
<%= data.time %>
Now, this isn’t very useful. Is it possible to run inline code inside of an EJS tag? Something like this:

<script>
moment.format()
var tz = getTimeZone()
</script>

<%= 
data.time.format(tz)
%>

Note that the code above doesn’t actually work it’s just the general idea of what should be happening. Would it work?

Hi @CarlyRaeJepsenStan,

There are different types of EJS tags which allows you to do certain things like execution, output, etc. What you’re trying to do is execute code and then output the results.

For that, EJS offers two different tags for these 2 purposes:

  1. <% - for code execution, no output allowed

  2. <%= - for output (HTML escaped)

So, you can execute your necessary code like this:

<%
moment.format()
var tz = getTimeZone()
%>

When I say code execution, you can do anything you can do in a normal JavaScript client-side file. Yeah, you can do if statements, loops, functions; the possibilities are endless!

And then you can output stuff like this:

<%= tz %>

Hope this helps!

1 Like

Just a heads up, did you define this on an earlier line? That function does not seem to be a native js function.
Screenshot 2020-09-04 at 11.36.27 AM

^ #tenchars

1 Like

Thanks khalby!

1 Like