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

时间:2017-02-02 11:31:11

标签: javascript node.js loops express breadcrumbs

我想创建一些自动生成面包屑并将其传递给客户端的中间件(服务器端)。我正在使用把手作为模板引擎并表达我的路由。

说我有这样的路线:

/* GET home page. */
router.get('/services/heroku/standards', getBreadcrumbs, (req, res) => {
  res.render('index', {
    breadcrumbs: req.breadcrumbs,
  });
});

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

到目前为止我已创建此功能:

// 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.

,我希望这种预期的结果
const myJson = [
{
    breadcrumbName: "Services",
    breadcrumbUrl: "/services"
},
{
    breadcrumbName: "Heroku",
    breadcrumbUrl: "/services/heroku"
},
{
    breadcrumbName: "Standards",
    breadcrumbUrl: "/services/heroku/standards"
}

如果有更有效的方式获得此结果,请告诉我。

1 个答案:

答案 0 :(得分:2)

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

// 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();
    }