Include pug mixin from other view folder

牧云@^-^@ 提交于 2019-12-25 01:08:08

问题


I have set multiple view paths in my express application:

express.set('views',['/path1', '/path2', '/path3']);

When I am rendering my view, I want to include the pug file form path2 in path1.

# /path2/index.pug

include path1/mixin.pug

I can not find a solution for this problem.


回答1:


I didn't use express.set views.

Just do this in your pug file

include ../path1/mixin.pug (or without .pug can also work) eg include ../path1/mixin

Edit:

For those that down voted this, you know nothing jon snow.

My setup:
File: index.js in root project folder [NOTE there's no app.set('views', path.join(__dirname, 'view'))]

const express = require('express')
const app = express()
const PORT = process.env.PORT || 3000
app.use(express.static('public'))
app.set('view engine', 'pug')
// routing
app.use('/', require('./home/route'))
app.listen(PORT, console.log(`Server started on port ${PORT}`))

Folder: view (inside root folder)

Folder: part (inside view folder eg root/view/part)

File: mixin.pug (inside view folder eg root/view/part/mixin.pug

mixin pet(name)
  li.pet= name

Folder: template (inside view folder eg root/view/template)

File: main.pug (in root/view/template/main.pug)

doctype html
html
    head
    body
        h1 Hello template/main.pug
        block content

Folder: home (inside root folder eg root/home)

File: route.js (inside home folder eg root/home/route.js)

const express = require('express')
const app = module.exports = express()
app.get("/",(req,res)=>{
    res.render('../home/index')
  })

File: index.pug (inside home folder eg root/home/index.pug)

extends ../view/template/main
block content
    h1 Helllllo from home/index.pug
    include ../view/part/mixin
    +pet('you')
    +pet('know')
    +pet('nothing')
    +pet('jon')
    +pet('snow')

As you can see, this is the output localhost:3000

Absolute proof that it works WITHOUT express.set views, AND with include ../path1/mixin.pug

How it works:

  • root index.js file routes to folder home to file route.js, pulls the file index.pug.
  • index.pug pulls the template file main.pug. Then pulls the mixin.

"You know nothing jon snow"



来源:https://stackoverflow.com/questions/54481027/include-pug-mixin-from-other-view-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!