Coming from a JAVA background I found EJS interesting. However, I can't seem to figure out how to get an object from a different function while looping. In the example bellow, I'm trying to call an async function in ReadingLog called chapters which queries a database and returns the chapters for each book:
<%
entries.forEach(function(i){
let chapters = await ReadingLog.chapters(i.book_uid);
total_mins=parseFloat(total_mins) parseFloat(i.minutes);
console.log('Date:' i.date.toDate().toISOString());
let tzdate = datetimeutil.converttz(i.date.toDate(),"America/Montreal");
let mdate = datetimeutil.convert_to_str(i.date.toDate());
%>
<tr>
<td><%= mdate %></td>
<td><%= i.book_title %></td>
<td>
<% if(i.language!=null && i.language == "fr"){ %>Fran&c¸ais<% } %>
<% if(i.language!=null && i.language == "en"){ %>English<% } %>
<% if(i.language!=null && i.language == "es"){ %>Español<% } %>
</td>
%>
Anyway to make it happen in EJS?
Thanks
CodePudding user response:
Never "make things happen" in EJS, that's not its job. You prepare all your data in your Node.js code, and then you pass that to EJS as templating context so it can be templated in.
So in this case: get your chapters data on the Node side, and then you render the response:
app.get(`whatever`, ..., async (req, res) => {
const entries = wherever.this.comesFrom();
// first, prep all your data for templating
const data = await Promise.all(
entries.map((entry, i) => {
return new Promise(resolve => {
const chapter = await ReadingLog.chapters(id);
const totalMins = ...;
...
resolve({ i, chapter, totalMins, ... });
});
});
// then just pass that data to your templating engine of choice.
res.render(`yourtemplate.html`, { entries: data });
});
And then EJS just needs to loop through entries and blindly write values into your template, with at most some for loops to generate properly wrapped data.
