问题描述
是否存在一种干净的建议方式从模板内部访问安装路径,因此快速应用程序既可以独立运行,也可以作为其他应用程序的一部分运行(通过app.use),路径指向正确的目标吗?
类似于:
{{mountpath }} route / to / file
因此,在应用程序独立运行的情况下,mountpath将会 /
,并且在作为子模块运行的情况下,mountpath可以是 / foo /
注意:我使用的是句柄。
我有同样的问题 - 需要使用
适用于我的解决方案基于2个事实
- mountpath在请求中可用 - req.baseUrl
- 响应本地对象被导出到模板 - res.locals
首先,创建一个单行中间件 - 这样做适用于模块/子应用程序中的所有路由
$ b $ pre $ router.use(函数(req,res,next){
res.locals.baseUrl = req.baseUrl;
next();
});
然后在模板中使用#{baseUrl} / some / route
- 请注意,这是jade的语法,但我想它和handlebar一样。
Is there a clean, recomended way to access the mountpath from inside a template, so an express app can be run both standalone and as a part of another app (by means of app.use), with the paths pointing to the correct destination either way?
Something like:
{{mountpath}}route/to/file
So in the case that the app is running standalone, mountpath will be /
, and in case is running as a submodule, mountpath could be /foo/
Note: I'm using handlebars.
I had the same issue - needed to use mountpath from inside a template.
Solution that works for me is based on 2 facts
- mountpath is available in request - req.baseUrl
- response locals object gets exported to the template - res.locals
First, create a one-line middleware - this will apply to all routes inside the module/subapp
router.use(function (req, res, next) {
res.locals.baseUrl = req.baseUrl;
next();
});
Then inside the template use #{baseUrl}/some/route
- note that this is jade syntax, but I suppose it works the same way with handlebars.
这篇关于使用express访问模板内的mountpath变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!