Skip to content

How to import a JSON file on template? #1178

Answered by cossssmin
didiraja asked this question in Q&A
Discussion options

You must be logged in to vote

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.

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@didiraja
Comment options

Answer selected by didiraja
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #1177 on February 10, 2024 13:03.