maizzle/framework

How to import a JSON file on template?

didiraja opened this issue · 1 comments

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.

  • config.js
const dataOne = require('./src/path/data-one.json')
const dataTwo = require('./src/path/data-two.json')
const dataThree = require('./src/path/data-three.json')

module.exports = {
  build: {
    // build config object
  },
  locals: {
  // locals variables
  },
  data: {
    dataOne,
    dataTwo,
    dataThree,
  }
}
  • templates/email.html
<p>{{page.data.dataOne.first_name}}</p>

Is it possible to achieve that using Front Matter syntax?

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.