maizzle / framework

Quickly build HTML emails with Tailwind CSS.
https://maizzle.com
MIT License
1.24k stars 49 forks source link

How to import a JSON file on template? #1177

Closed didiraja closed 9 months ago

didiraja commented 9 months ago

I'm creating a series of ecommerce emails that uses a huge load of data, as including all this variables on top of files is not an option, I'd like to load this data from a JSON file.

Couldn't find anything on docs of both Maizzle or Front Matter to do that. There's just a few instructions about which expressions is allowed on top of template files.

My workaround is loading JSON files on config.js but whenever I change content from JSON, rendered e-mail does reload but only html content not data from JSON. Forcing me to stop and restart process.

module.exports = { build: { // build config object }, locals: { // locals variables }, data: { dataOne, dataTwo, dataThree, } }

- **templates/email.html**

{{page.data.dataOne.first_name}}



Is it possible to achieve that using Front Matter syntax?
cossssmin commented 9 months ago

In order to refresh the JSON data you could use the beforeCreate event hook to delete the require cache (see SO answer) or simply re-fetch the file, JSON.parse() it, and add it to the config, which may be simpler... maybe like this:

const fs = require('node:fs/promises')

module.exports = {
  events: {
    async beforeCreate(config) {
        // read the file
        let data = await fs.readFile('data.json', 'utf8')
        // set it in the config, so you can use `page.?` to render it
        config.locals = JSON.parse(data)
    }
  }
}

Front Matter can't do this, it's only used to define or override existing data when coding a Template in Maizzle.