Multiple View paths on Node.js + Express

前端 未结 5 1602
一向
一向 2020-12-02 15:25

I\'m writing a CMS on Node.js with Express Framework. On my CMS I have several modules for users, pages, etc.

I want that each module will have his

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 16:05

    Install glob npm install glob

    If you have a views directory that looks something like:

    views
    ├── 404.ejs
    ├── home.ejs
    ├── includes
    │   ├── header.ejs
    │   └── footer.ejs
    ├── post
    │   ├── create.ejs
    │   └── edit.ejs
    └── profile.ejs
    
    

    You can use this glob function to return an array of subdirectories in the views directory (add the path.substring to remove the trailing /)

    let viewPaths = glob.sync('views/**/').map(path => {
        return path.substring(0, path.length - 1)
    })
    
    
    console.log(viewPaths)
    >> ['views', 'views/post', 'views/includes']
    

    So now you can set

    app.set('views', viewPaths)
    

    and now you can use

    res.render('404')
    res.render('home')
    res.render('post/edit')
    res.render('post/create')
    

提交回复
热议问题