eiskalteschatten / typescript-static-blog

This is a boilerplate project for a blog based on static Markdown files using TypeScript, Fastify and EJS.
https://www.alexseifert.com
0 stars 0 forks source link

It's not a bug #1

Open clabnet opened 4 months ago

clabnet commented 4 months ago

Hi, I need to format datetime into an EJS template, using @fastify/view v9.0.0. I think to create an helper with my function and pass it on the fastify.view command const htmlContent = await fastify.view(template, { rfq } ) I have add an hook as is :

declare module 'fastify' {
  interface FastifyReply {
    locals: {
      helpers: any
    }
  }
}
 fastify.addHook('preHandler', (request, reply, done) => {
    // Global variables for the EJS templates can be set here
    reply.locals = {
      helpers: ejsHelpers
    }
    done()
  })

where ejsHelpers contains my custom "formatLocaleDateTime" function. So, how to pass the helper so that its functions are usable during the rendering phase of the EJS template? My goal is to use : <%= helpers.formatLocaleDateTime (date()) %> The error is helpers is not defined.

With best compliments for your work. Thank you.

eiskalteschatten commented 4 months ago

The way I did it here: https://github.com/eiskalteschatten/typescript-static-blog/blob/main/src/app.ts works for me and I do use it in my ejs files (for example, here: https://github.com/eiskalteschatten/typescript-static-blog/blob/main/templates/_blog/post.ejs). How are you importing your helpers?

If you have a loose collection of functions (like in https://github.com/eiskalteschatten/typescript-static-blog/blob/main/src/lib/ejsHelpers.ts), then you will need to import it with a like this: `import as ejsHelpers from './lib/ejsHelpers';`

clabnet commented 4 months ago

@eiskalteschatten I have a plugin with this preHandler hook:

import * as ejsHelpers from '../composables/ejsHelpers'    <<< import here
declare module 'fastify' {
  interface FastifyReply { locals: { helpers: any }  }
}
fastify.addHook('preHandler', (request: RequestCompose, reply: FastifyReply, done: DoneFuncWithErrOrRes) => {
    reply.locals = { helpers: ejsHelpers  }      <<< add helpers to reply
    done()
  })

The controller is :

export default fp(async (fastify: FastifyInstance, opts: FastifyPluginOptions) => {
  fastify.post('/mail/compose', { schema: composeSchema }, async function (request: RequestCompose, reply) {
... validate and get qs and body from the request ...
... get template name ...
... preparing rfqItems data ...
      fastify.log.debug({ rfq, rfqItems }, 'Preparing mail body...')
      const htmlContent = await fastify.view(template, { rfqItems })   <<< merge template with data
      fastify.log.debug({ html: htmlContent }, 'Data merged to mail body')
... send reply 200 ...      

I missed any thing ? Thank's for your reply.