Workaround to dynamic includes in Pug/Jade

前端 未结 3 1577
粉色の甜心
粉色の甜心 2021-01-20 23:59

I understand that Pug does not support dynamic includes or extends in templates. Ie

extend path/to/template 

works but not

ex         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 00:59

    In order to do dynamic include, you will have to use Unescaped String Interpolation, inserting pug contents that are pre-compiled before your main .pug file inside your route. In other words it works as follows:

    1) Some .pug files are pre-compiled into HTML 2) The HTML gets fed into another .pug file compilation process

    Here's an example how to do it

    Inside your router file (routes.js or whatever)

    var pug = require('pug')
    var html = []
    var files = ['file1','file2'] // file names in your views folders
    let dir = path.resolve(path.dirname(require.main.filename) + `/app/server/views/`)
    //dir is the folder with your templates
    app.get('/some-route', (req,res) => {
        for (let n = 0; n < files.length; n++) {
    
            let file = path.resolve(dir + '/' + files[n] + `.pug`)
            fs.access(file, fs.constants.F_OK, (err) => {
                if (!err) {
                    html.push(pug.renderFile(file, data))
                    if (n === files.length - 1) {
                        res.render('dashboard', {html})
                    }
                }
                else {
                    res.status(500).json({code:500,status:"error", error:"system-error"})
                }
            })
        }
    })
    

    Inside your desired .pug file:

    for item in html
        .
            !{item}
    

    The example above is specific to my own use case, but it should be easy enough to adapt it.

提交回复
热议问题