我知道Pug不支持动态包含或在模板中扩展。即
extend path/to/template 起作用但不起作用
extend #{dynamic_path_to_template}是否有一个解决办法(无论多么复杂)允许在运行时修改视图使用的模板的相同目标?
Context:我的用例是,我正在开发一个npm模块,用于扩展其他视图的模板位于模块中。在模块发布和安装之后,将定义路径(即。但在开发阶段,我只需要能够"npm链接“到模块并让模板工作。我也不喜欢硬编码链接,这样我就可以发布与测试相同的代码。
发布于 2020-07-14 12:05:26
我也有这个问题,并在寻找解决办法时发现了这个问题。我的解决方案类似于尼古拉·桑伯格的回答,但我想我应该分享一下。
我创建了一个函数,通过给模板一个路径来呈现模板,并将其传递给options对象。也许这对你的情况也有帮助
const includeFunc = (pathToPug, options = {}) => {
return pug.renderFile(pathToPug, options); //render the pug file
}
const html = pug.renderFile('template.pug', {include: includeFunc});然后按照模板中的如下方式使用:
body
h1 Hello World
|!{include(dynamicPugFilePathFromVariable)}发布于 2017-08-22 20:01:09
目前还没有办法做到这一点,但是您可以在没有动态扩展的情况下完成应用程序体系结构。
可能的解决方案#1
layout.jade,并在控制器(true/false)中定义conditionalVariable:
view.jade:扩展布局块内容p,这里是我的内容!可能的解决方案#2
可能的解决方案#3
使用类似于terraform的东西,它使用pug作为它的呈现引擎,但它使您能够使用如下动态部分
!= partial(dynamicFileFromVariable)发布于 2021-02-12 12:06:15
它起作用了!
首先,设置res.locals中间件.
middlewares/setResLocals.js
const pug = require('pug')
const path = require('path')
module.exports = function(req, res, next) {
res.locals.include = (pathToPug, options = {}) => { // used for imitate includ pug function
return pug.renderFile(pathToPug, options); //render the pug file
}
res.locals.__PATH__ = path.join(__dirname, '../')
next()
}server/index.js
app.use(require('../middlewares/setResLocals'))file.pug
|!{include(`${__PATH__}/${something}`)}https://stackoverflow.com/questions/45824697
复制相似问题