使用express访问模板内的mountpath变量 [英] Access to mountpath variable from inside a template using express

查看:350
本文介绍了使用express访问模板内的mountpath变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种干净的建议方式从模板内部访问安装路径,因此快速应用程序既可以独立运行,也可以作为其他应用程序的一部分运行(通过app.use),路径指向正确的目标吗?

类似于:

  {{mountpath }} route / to / file 

因此,在应用程序独立运行的情况下,mountpath将会 / ,并且在作为子模块运行的情况下,mountpath可以是 / foo /



注意:我使用的是句柄。

解决方案

我有同样的问题 - 需要使用



适用于我的解决方案基于2个事实


  1. mountpath在请求中可用 - req.baseUrl

  2. 响应本地对象被导出到模板 - 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

  1. mountpath is available in request - req.baseUrl
  2. 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变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆