This is not a duplicate.I would like to be able to perform await in a constancy in my ejs file, but I have the famous error: SyntaxError: await is only valid in async function in C:\\Users\\...\\dashboard.ejs while compiling ejs
Could you explain to me how it works and how I can fix my code? :
app.js
let ejsOptions = {
// delimiter: '?', Adding this to tell you do NOT use this like I've seen in other docs, does not work for Express 4
async: true
};
// We set out templating engine.
app.engine("html", async (path, data, cb) => {
try{
let html = await ejs.renderFile(path, data, ejsOptions);
cb(null, html);
}catch (e){
cb(e, '');
}
});
app.get("/dashboard", checkAuth, async (req, res) => {
await renderTemplate(res, req, "dashboard.ejs", { perms: Discord.Permissions });
});
dashboard.ejs :
<%
let results;
results = await bot.shard.broadcastEval(`this.guilds.cache.get('${guild.id}')`);
console.log(results.id)
if (results) {
%>
<a class="button is-success has-text-centered" href="/dashboard/<%= guild.id %>">Settings</a>
<% } else { %>
<a class="button is-primary has-text-centered" href="<%= `https://discordapp.com/oauth2/authorize?client_id=${bot.user.id}&scope=bot&guild_id=${guild.id}&response_type=code&redirect_uri=${encodeURIComponent(`${bot.config.domain}${bot.config.port == 80 ? "" : `:${bot.config.port}`}/callback`)}` %>">Invite</a>
<% }
%>
<% }); %>
<%- include("partials/footer") %>
</section>
I have tried many methods, but when I try to use 'if' 'else' no results appear.
you get resultes data before render ejs file like this.
app.js
app.get("/dashboard", checkAuth, async (req, res) => {
const data = await bot.shard.broadcastEval(`this.guilds.cache.get('${guild.id}')`);
renderTemplate(res, req, "dashboard.ejs", { perms: Discord.Permissions, data });
});
dashboard.ejs
.... your code.....
if (data != undefined) || data != null) {
%>
<a class="button is-success has-text-centered" href="/dashboard/<%= guild.id %>">Settings</a>
<% } else { %>
<a class="button is-primary has-text-centered" href="<%= `https://discordapp.com/oauth2/authorize?client_id=${bot.user.id}&scope=bot&guild_id=${guild.id}&response_type=code&redirect_uri=${encodeURIComponent(`${bot.config.domain}${bot.config.port == 80 ? "" : `:${bot.config.port}`}/callback`)}` %>">Invite</a>
<% }
%>
<% }); %>
<%- include("partials/footer") %>
</section>
some changes according to requirement.!!!
You need to prepare all render data needed by the template before rendering it. For your results
example, it would be something like:
app.get("/dashboard", checkAuth, async (req, res) => {
const results = await bot.shard.broadcastEval(`this.guilds.cache.get('${guild.id}')`);
renderTemplate(res, req, "dashboard.ejs", { perms: Discord.Permissions, results });
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.