首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JavaScript - Express JS -动态面包屑创建(名称+ URL)

JavaScript - Express JS -动态面包屑创建(名称+ URL)
EN

Stack Overflow用户
提问于 2017-02-02 19:31:11
回答 1查看 2.8K关注 0票数 3

我想创建一些中间件(服务器端),将自动生成面包屑,并通过客户端。我使用把手作为模板引擎,使用express作为我的路由。

假设我有一条这样的路由:

代码语言:javascript
运行
复制
/* GET home page. */
router.get('/services/heroku/standards', getBreadcrumbs, (req, res) => {
  res.render('index', {
    breadcrumbs: req.breadcrumbs,
  });
});

我想有一个中间件函数,它通过并获得req.originalUrl,然后用它创建一个JSON对象/面包屑数组。

到目前为止,我已经创建了这个函数:

代码语言:javascript
运行
复制
// Function for getting breadcrumbs of the page
function getBreadcrumbs(req, res, next) {
  // Initizating the JSON Object.
  const myJson = {};
  // Getting the URL and splitting the variables into an Array.
  const pathArray = req.originalUrl.split('/');
  // Removing the first value in the array as it will be empty.
  pathArray.shift();
  // Getting the length of the array.
  const arrayLength = pathArray.length;
  // Looping through the array and pushing value to the Json Object
  for (let i = 0; i < arrayLength; i++) {
    // Adding the breadcrumb name E.G home
    myJson.breadcrumbName = pathArray[i];
    // Adding the breadcrumb URL E.G /home/heroku/standards - **TROUBLE HERE!!!!!**
    myJson.breadcrumbUrl = req.originalUrl;
  }
  // Storing the array above in the request.
  req.breadcrumbs = pathArray;
  // If the request is the home page we need to change the value to: Home
  if (req.breadcrumbs[0] === '') {
    // Change the value of the first array to Home
    req.breadcrumbs[0] = 'Home';
  }
  // Finished the middleware request.
  next();
}

如果网址是:/services/heroku/standards.,我希望会出现这样的预期结果

代码语言:javascript
运行
复制
const myJson = [
{
    breadcrumbName: "Services",
    breadcrumbUrl: "/services"
},
{
    breadcrumbName: "Heroku",
    breadcrumbUrl: "/services/heroku"
},
{
    breadcrumbName: "Standards",
    breadcrumbUrl: "/services/heroku/standards"
}

如果有更有效的方法来获得这个结果,请告诉我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-03 00:22:42

找到答案了。这将把面包屑存储到req.breadcrumbs

代码语言:javascript
运行
复制
// Function for getting breadcrumbs of the page
    function getBreadcrumbs(req, res, next) {
      const urls = req.originalUrl.split('/');
      urls.shift();
      req.breadcrumbs = urls.map((url, i) => {
        return {
          breadcrumbName: (url === '' ? 'Home' : url.charAt(0).toUpperCase() + url.slice(1)),
          breadcrumbUrl: `/${urls.slice(0, i + 1).join('/')}`,
        };
      });
      next();
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42001095

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档