[英]How can I use await in ejs file?
这不是重复的。我希望能够在我的 ejs 文件中持续执行 await,但我有一个著名的错误: SyntaxError: await is only valid in async function in C:\\Users\\...\\dashboard.ejs while compiling ejs
你能向我解释它是如何工作的以及我如何修复我的代码吗? :
应用程序.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 });
});
仪表板.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>
我尝试了很多方法,但是当我尝试使用 'if' 'else' 时没有结果出现。
在像这样渲染 ejs 文件之前,您会获得结果数据。
应用程序.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 });
});
仪表板.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>
根据要求进行一些更改。!!!
您需要在渲染之前准备模板所需的所有渲染数据。 对于您的results
示例,它将类似于:
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 });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.