在 Express 中将菜单渲染为 Jade 视图部分

发布于 2024-12-25 10:52:14 字数 313 浏览 2 评论 0原文

我无法概念化如何使用 Jade 视图部分在 Express 应用程序中渲染具有活动状态的菜单。

我有这样的事情:

ul.menu
  li
    a(href='/some/route').active
  li
    a(href='/another/route')

我想要的是将 .active 类应用于当前路由,以便我的 CSS 可以呈现活动的 UI 状态。

当我用 PHP 编写时,这可以通过一些复杂的 if/else 语句链来完成,但我假设有一种更优雅的方法。我缺少什么?

I'm having trouble conceptualizing how to render menus with active states in an Express app using Jade view partials.

I have something like this:

ul.menu
  li
    a(href='/some/route').active
  li
    a(href='/another/route')

What I'd like is for the .active class to be applied to the current route, so my CSS can render an active UI state.

When I wrote in PHP, this would've been accomplished through some complex chain of if/else, statements, but I'm assuming there's a more elegant approach. What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你如我软肋 2025-01-01 10:52:14

我的解决方案与 danmactough 的类似,但我认为更简洁。

我使用中间件将 url 保存为所有请求的本地变量。确保它出现在您的路线之前。

app.use(function(req, res, next) {
  res.locals.url = req.url;
  next();
});

我的 Jade 菜单模板如下所示

ul
  each link in links
    li
      a(href=link.url, class=link.url === url && 'active')= link.name

My solution is similar to danmactough's, but I think a little tidier.

I use middleware to save the url as a local variable on all requests. Make sure this comes before your routes.

app.use(function(req, res, next) {
  res.locals.url = req.url;
  next();
});

My Jade template for a menu looks like this

ul
  each link in links
    li
      a(href=link.url, class=link.url === url && 'active')= link.name
哆兒滾 2025-01-01 10:52:14

杰德对路线一无所知。我认为没有任何方法可以避免某种形式的 if/else。

在 Express 中,只需将路线作为本地传递即可:

res.render('my_view', {
  current: 'current/url'
});

在视图中,有一系列菜单链接并执行以下操作:

ul.menu
  for each item in links
    li
      if (item.url == current)
         a(href=item.url).active
      else
         a(href=item.url)

Jade is ignorant about the route. I don't think there's any way to avoid the if/else in one form or another.

In Express, just pass the route as a local:

res.render('my_view', {
  current: 'current/url'
});

And in the view, have an array of menu links and do something like:

ul.menu
  for each item in links
    li
      if (item.url == current)
         a(href=item.url).active
      else
         a(href=item.url)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文