<script src="https://unpkg.com/dayjs"></script>
<%
dayjs().format()
var d = post.date
var time = dayjs(d).format("MMM DD, YYYY - HH:mm:ss (hh:mm:ss A)")
%>
<p><b>Title:</b><%-post.title%></p>
<br>
<p><b>Content:</b><%-post.body%></p>
<p><b>Date posted:<b/><%-time%></p>
This code doesn’t render right - it serves an error: dayjs is not defined
I tried putting the dayjs code in script tags - it runs alright, but now “time” is not defined.
How can I use an external lib with EJS?
The script tags are a script to run on the client.
The <% … %> tags are run on the server, or the client if you want.
So you can do either:
a. Calculate the time on the client
or
b. Use require
to bring in a module on the server
or
c. Configure EJS to run in the browser
How are you using EJS?
I need to run DayJS on the client because the lib automatically detects the client time zone - this can’t happen on the server.
Maybe I could do this:
var dayjs = require("dayjs")
app.get(...
res.render("uniquepost", {
dayjs: dayjs,
title: post.title,
body: post.body
})
I guess because dayjs is only 2kb it wouldn’t take too long to load. What do you think?
How about the server passes the date value to javascript in the client … I’m not sure what format <%-post.date%>
will be, should work if it is like 1600666077974.
<script src="https://unpkg.com/dayjs"></script>
<p><b>Title:</b><%-post.title%></p>
<br>
<p><b>Content:</b><%-post.body%></p>
<p><b>Date posted:</b><span id="posttime"></span></p>
<script>
dayjs().format()
var time = dayjs(<%-post.date%>).format("MMM DD, YYYY - HH:mm:ss (hh:mm:ss A)")
document.getElementById("posttime").textContent = time;
</script>
1 Like
That’s a smart idea - I didn’t know you could use EJS tags in script tags! I’ll try this out right now.
Ok, it actually doesn’t work…
-
<%- post %>
is succesfully passed - it forms an [object Object]
- However, for some reason it’s undefined - dayjs appears client side with no arguments.
- So then I just tested
var obj = <%- post %>

This is sadly not working, so I’m probably going to try to use fetch and start a GET endpoint on my web app to get the time.
If post.date is a date object, you could pass the milliseconds string to the script via
<%-post.date.getTime()%>
Otherwise your idea to fetch it later should work.
1 Like
post.date
is a number like 1566039843. I’ll just have to do complex acrobatics like parse the sent URL, and fetch with the id, and this and that rip.
Another alternative is render post.date to a hidden HTML element, then pull its value with javascript.
Are you sure? What does this show
console.log(typeof post.date)
1 Like
I just checked out the EJS docs, and there’s a possibility we’ve been using the wrong tags. The docs show obj.key in <%= tags. I’m testing that right now.

Orange means number, green means string, etc.
So <%= post %>
returns nothing, and <%= post.date %>
returns object Object.
What I can do is set a div to be post.date, and then use a window.onload function to get the value of the div.