You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Express和Express-Handlebars中为导航链接添加激活样式

在Express + Express-Handlebars中给导航链接添加激活样式

要实现导航链接的激活状态(当前页面链接高亮),推荐通过服务器端Handlebars模板逻辑处理,比前端JS更可靠(避免页面刷新丢失状态),具体步骤如下:

1. 路由中传递当前路径给模板

在每个Express路由渲染页面时,把当前请求的路径(req.path)作为变量传给模板,让Handlebars能识别当前页面:

// 示例:/warum路由
app.get('/warum', (req, res) => {
  res.render('warum', {
    currentPath: req.path, // 直接获取当前请求路径
    admin: req.session?.admin || false // 保留原有admin变量
  });
});

// 其他路由同理,比如/was
app.get('/was', (req, res) => {
  res.render('was', {
    currentPath: req.path,
    admin: req.session?.admin || false
  });
});

2. 注册Handlebars自定义辅助函数

在Express配置Handlebars的位置,注册一个isActive辅助函数,用来判断链接是否为当前活跃状态:

const express = require('express');
const exphbs = require('express-handlebars');
const app = express();

// 配置Handlebars并注册辅助函数
const hbs = exphbs.create({
  helpers: {
    isActive: function(currentPath, linkPath) {
      // 当前路径与链接路径匹配时返回active类,否则返回空
      return currentPath === linkPath ? 'active' : '';
    }
  }
});

app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

3. 修改导航栏模板代码

在导航的<a>标签中,通过isActive辅助函数动态添加激活类:

<ul class="links">
  <li><a class="nav-anch {{isActive currentPath '/warum'}}" href="/warum">Warum</a></li>
  <li><a class="nav-anch {{isActive currentPath '/was'}}" href="/was">Was</a></li>
  <li><a class="nav-anch {{isActive currentPath '/wer'}}" href="/wer">Wer</a></li>
  <li><a class="nav-anch {{isActive currentPath '/aktuelles'}}" href="/aktuelles">Aktuelles</a></li>
  <li><a class="nav-anch {{isActive currentPath '/referenzen'}}" href="/referenzen">Referenzen</a></li>
  {{#if admin}}
  <li><a class="nav-anch {{isActive currentPath '/logout'}}" href="/logout">Ausloggen</a></li>
  {{else}}
  <li><a class="nav-anch {{isActive currentPath '/kontakt'}}" href="/kontakt">Kontakt</a></li>
  {{/if}}
</ul>

4. 添加CSS激活样式

在样式表中定义active类的高亮样式:

.nav-anch.active {
  color: #e74c3c; /* 自定义激活颜色 */
  font-weight: 700;
  border-bottom: 2px solid #e74c3c;
}

替代方案:无需自定义辅助函数

如果不想注册辅助函数,也可以用Handlebars内置的eq比较器(需确保版本支持):

<a class="nav-anch {{#if (eq currentPath '/warum')}}active{{/if}}" href="/warum">Warum</a>

通过以上步骤,页面加载时会自动给当前页面的导航链接加上激活样式,完全适配Express-Handlebars的服务端渲染逻辑。

内容的提问来源于stack exchange,提问作者DragoO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:53:17