Global View function in mail view render


#1

Trying to use a custom View.globals() function in my .edge template for a .html formatted email.

I’ve created a middleware that defines some custom functions like:

    View.global('currentYear', () => {
      return moment().format('YYYY')
    })

However, it looks like in the mail render, these functions can’t be found.

It seems like the renderer inside adonis-mail is unaware of any middleware:

Is there a way to inject any middleware into mail?


#2

ok, I figured this out. I need to inject my View.globals earlier in the lifecycle, so I added this to hooks.js:

const { hooks } = require('@adonisjs/ignitor')

hooks.after.providersBooted(() => {
  /**
   * This is a little strange... middleware only runs on named routes, so what
   * happens if there is a 404 error because the client is invoking an undefined
   * route? should the error handler invoke any other
   * classes?
   *
   * In this example, ViewGlobalMiddleware defines our custom View.globals()
   * however in a 404 error, the middleware is not invoked. So we need to do this here...
   * or is this a duplicated effort? should we remove it from the kernel.js configuration?
   *
   * ref: http://adonisjs.com/docs/4.1/http-context
   */
  make('App/Middleware/ViewGlobalMiddleware')
})