Access to mountpath variable from inside a templat

2019-08-08 19:52发布

问题:

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.

回答1:

express.static middleware is responsible for serving the static assets of an Express application. How it works:

  • Serve static content for the app from the "public" directory in the application directory

    // GET /style.css etc

    app.use(express.static(__dirname + '/public'));

  • Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static"

    // GET /static/style.css etc.

    app.use('/static', express.static(__dirname + '/public'));

  • Serve static files from multiple directories, but give precedence to "./public" over the others

    app.use(express.static(__dirname + '/public'));

    app.use(express.static(__dirname + '/files'));

    app.use(express.static(__dirname + '/uploads'));

In your case you can use the second case i.e.; mounting files on path '/static', so whatever files are under the folder public can be accesses with src='/static/filename.xyz' Create a folder name public with sub folders css, js, images Or if you want your css to be mounted on path /css then you do :

app.use('/css',express.static(path.join(__dirname, 'module1/css')));

Now you can use all your css files in your entire application as :

 <link href="css/style.css" rel="stylesheet">


回答2:

There is an event that is fired after the module is mounted, so I can do:

app.locals.modulePath = "/";

app.on('mount', function (parent) {
  app.locals.modulePath = app.mountpath;
});

The locals are directly accessible from inside all the views, so this will be accessible like {{modulePath}}



回答3:

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.