Javascript Pug/Jade中动态包含的变通方法
我知道帕格不支持模板中的动态包含或扩展。即Javascript Pug/Jade中动态包含的变通方法,javascript,node.js,templates,pug,pugjs,Javascript,Node.js,Templates,Pug,Pugjs,我知道帕格不支持模板中的动态包含或扩展。即 extend path/to/template 有效但无效 extend #{dynamic_path_to_template} 是否有一种变通方法(无论多么复杂)可以实现在运行时修改视图使用的模板的相同目标 上下文:我的用例是开发一个npm模块,用于扩展其他视图的模板位于模块内部。发布和安装模块后,将定义路径(即node_modules/my_module/path/to/template),但在开发阶段,我只需要能够“npm link”到模块
extend path/to/template
有效但无效
extend #{dynamic_path_to_template}
是否有一种变通方法(无论多么复杂)可以实现在运行时修改视图使用的模板的相同目标
上下文:我的用例是开发一个npm模块,用于扩展其他视图的模板位于模块内部。发布和安装模块后,将定义路径(即node_modules/my_module/path/to/template),但在开发阶段,我只需要能够“npm link”到模块并使模板工作。我也不想硬编码的链接,所以我可以发布相同的代码测试 目前还没有办法做到这一点,但您可以在不使用动态扩展的情况下构建应用程序体系结构 可能的解决方案#1
layout.jade:
if conditionalVariable
include firstLayout.jade
else
include otherLayout
layout.jade
,并在控制器中定义conditionalVariable
(true
/false
):
- var lang = req.getLocale();
doctype html
block modifyLayout
extends ../layout
block modifyLayout
- var lang = "en" //force language to be en in this page.
block body
include my-page-body
!= partial(dynamicFileFromVariable)
为了实现动态include,您必须使用Unescaped字符串插值,在路由中插入在main.pug文件之前预编译的pug内容。换句话说,它的工作原理如下: 1) 一些.pug文件被预编译成HTML 2) HTML被输入到另一个.pug文件编译过程中 下面是一个如何做到这一点的示例 在路由器文件中(routes.js或其他文件)
上面的例子是针对我自己的用例的,但它应该很容易适应。我也有这个问题,在寻找解决方案时发现了这个问题。我的解决方案类似于尼古拉·沙姆伯格的答案,但我认为我应该分享它 我创建了一个函数,通过给它一个路径并将其传递给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)}
它起作用了
首先,设置分辨率。
middleware/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()
}
app.use(require('../middlewares/setResLocals'))
server/index.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()
}
app.use(require('../middlewares/setResLocals'))
file.pug
|!{include(`${__PATH__}/${something}`)}
解决方案#1和#2看起来不错,只是它们需要了解可能的模板文件的位置。我的用例是,我正在开发一个npm模块,模板在模块内部。发布和安装模块后,将定义路径(即node_modules/my_module/path/to/template),但在开发阶段,我只需要能够“npm link”到模块并使模板工作。我也不希望硬编码链接,这样我可以发布与测试相同的代码。在运行pug渲染器之前,您可以使用环境知道其位置的动态路径将pug文件写入文件系统。这是如何工作的?您是否建议在初始化序列中执行类似“fs.writeFile(/known/location/my_template.pug)”的操作,然后使用新创建的pug文件模板扩展我的视图?如果是这样,我认为帕格要求所有文件在运行时立即可用,因为所有文件都加载到内存中。
|!{include(`${__PATH__}/${something}`)}