在express.js中为每个请求设置全局res.local变量

时间:2020-12-28 16:49:10

Basically I want to build a site wide navigation bar that contains links as specified in the local variables in express.js

基本上,我想构建一个站点范围的导航条,其中包含在express.js中的局部变量中指定的链接

So I build my list of links I want to include on a page:

所以我把我想要包含在页面上的链接列出来:

class NavigationLink
  constructor: (@title,@url) ->

app.use (req,res,next) ->
  res.locals.navigationLinks = [
    new NavigationLink "About", "/about"
    new NavigationLink "Projects", "/projects"
    new NavigationLink "Skills", "/skills"
    new NavigationLink "Contact", "/contact"
  ]
  next()

Then if I hit the home page:

如果我点击主页:

app.get '/', (req,res) ->
  res.render('about')

Jade tries to render this layout file, which is supposed to loop through the navigationLinks array and render for each one:

Jade试图呈现这个布局文件,它应该通过navigationLinks数组循环,并为每个布局文件呈现:

!!! 5
html
include header
body
    .container
        .row
            .span3
                ul.nav.nav-tabs.nav-stacked
                    for navigationLink in navigationLinks
                        include navigationLink
            .span9
                block content

However I am getting a reference error 'navigationLinks is not defined' which I assume to mean to mean the locals aren't getting passed through. Would love advice on how to fix the problem, or another design paradigm that is better suited for this kind of thing (dynamic building of links on every page of the site). Thanks!

但是我得到了一个引用错误“导航链接没有定义”,我认为这意味着本地用户没有通过。我们希望得到关于如何解决问题的建议,或者其他更适合这种情况的设计范例(在站点的每个页面上动态构建链接)。谢谢!

1 个解决方案

#1


3  

Jonathan Ong is correct. Your code above should work in the default middleware order which would run all the app.use middleware before the app.router middleware. Thus I would agree that elsewhere in your code you probably have a line app.use app.router that comes before the app.use in your code snippet.

乔纳森·昂是正确的。上面的代码应该以默认的中间件顺序运行,该顺序将在app.router之前运行所有应用程序。因此,我同意在代码的其他部分,您可能有一个行应用程序。使用app.router,它在app.use之前。

#1


3  

Jonathan Ong is correct. Your code above should work in the default middleware order which would run all the app.use middleware before the app.router middleware. Thus I would agree that elsewhere in your code you probably have a line app.use app.router that comes before the app.use in your code snippet.

乔纳森·昂是正确的。上面的代码应该以默认的中间件顺序运行,该顺序将在app.router之前运行所有应用程序。因此,我同意在代码的其他部分,您可能有一个行应用程序。使用app.router,它在app.use之前。