0

I have a partial view that is used on server-side rendering to build a HTML page and also in FrontEnd to make a partial update on the UI. BecauseI want to use the same partial view file on both server-side and FrontEnd, I was looking for the best approach to share this file between the two sides.

For now, TBMK I used the following approach:

  • Placed the partial view file in /public folder which is served by express static middleware.
  • The server application loads the partial view from the file system.
  • The FrontEnd loads the partial via an AJAX HTTP request.

Is there any better approach?

Miguel Gamboa
  • 8,855
  • 7
  • 47
  • 94

1 Answers1

1

I've had a similar problem. My solution was to have a particular route (maybe even in a special controller, for separation of concerns sake) serving the ajax requests.

The controller is serving files from the views directory.

If you'd like to deliver e.g. a file from the app/viewsDir/partialsDir directory you'd use a URL like:

http://myhost.com/partials/my-partial

then controller the could respond like:

router.get('/partials/:partialName', function(req, res, next) {
    res.sendfile(`viewsDir/partialsDir/${req.params.partialName}`, 
    {root: __dirname });
});

This way, you could even have the file preprocessed by handlebars or any other serverside templating engine.

I did it this way, because I didn't want to have any templates located in the public directory.

LongHike
  • 4,016
  • 4
  • 37
  • 76