Skip to content

Global View Context #4

@arb

Description

@arb

It would be nice if you could specify a global context value that would be merged into the passed in view context. Ideally it would take an object or a function in case you needed to do some logic while setting up your global context.

Currently, the only way to set up a global context is via an extension point and checking the response type for view.


server.views({
  context: {
    version: '1.5.5',
    name: 'Application Name',
  }
});
//OR
server.views({
  context: function (request) {
    return {
      version: '1.4.5',
      date: Date.now(),
      id: request.id
    }
  }
});

The value of server.views.context would be merged with whatever context gets passed into reply.view. Any collision, the local one overwrites the gloabal context


reply.view('index', {
  test: 'This is the index view'
});

Would result in a context object of

{
  version: '1.5.5',
  name: 'Application Name',
  test: 'This is the index view'
}
//OR
{
  version: '1.4.5',
  date: <timewhencontextruns>,
  id: 5,
  test: 'This is the index view'
}

I think this is much clearer than the suggested approach in the tutorials that looks like this:

// Server extension points
server.ext('onPreResponse', function (request, reply) {

  if (request.response.variety === 'view') {
      request.response.source.context = Hoek.applyToDefaults(server.settings.app.globalContext, request.response.source.context || {});
      reply();
  }
  else {
      reply();
  }
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew functionality or improvement

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions