gpt4 book ai didi

node.js - Node - 将变量渲染到部分布局 ejs-locals 中

转载 作者:太空宇宙 更新时间:2023-11-04 01:44:42 24 4
gpt4 key购买 nike

我正在使用护照,我需要我的布局(使用 ejs-locals 'partial' )可以呈现我的用户名变量。

app.use(function(req, res, next) {
res.locals =
{
what : 'MyProject',
who : req.user.username
}
next();
});

我意识到'req.user.username'仅在'isAuthenticated'返回true时才可用。以下代码有效,但我确信有一种方便的方法,而不是为每个路由编写变量。

app.get('/dashboard',isAuthenticated, function(req, res) {
res.render('template/index', {who:req.user.username});
});

然后,这是我的布局:

<div id="wrapper">
<!-- Navigation -->
<nav style="margin-bottom: 0">

<%- partial('header.ejs') %>
<%- partial('left.ejs') %>

</nav>

<%- body %>
</div>

最后是我的 header.ejs

<span style='padding-left:18px'>Hi, <%=who%></span>

最佳答案

尝试使用<% include header.ejs %>反而。

这在 ejs 中有效,不确定 ejs-locals 是否相同。在 header.ejs 中,您应该有权访问 who 。值得尝试。

关于node.js - Node - 将变量渲染到部分布局 ejs-locals 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51900908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com