Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compile Templates on data change #20

Closed
kelvinlouis opened this issue Jun 14, 2017 · 3 comments
Closed

Compile Templates on data change #20

kelvinlouis opened this issue Jun 14, 2017 · 3 comments
Labels
feature feature request to implement

Comments

@kelvinlouis
Copy link

Hi,

Is it possible to compile the templates when the data (JSON) has been changed?

@kelvinlouis kelvinlouis changed the title [Question] Compile Templates on data change Compile Templates on data change Jun 14, 2017
@kelvinlouis
Copy link
Author

Currently, I am working around this the following way:

const fs = require('fs');
const chalk = require('chalk');

...
...
new HandlebarsPlugin({
  ...
  partials: [
        path.join(process.cwd(), "views", "partials", "**", "*.hbs"),
        path.join(process.cwd(), "views", "data", "**", "*.json")
  ],
  ...
  /**
     * Circumvent caching of require() and always access from file system.
   */
      onBeforeRender: function (Handlebars, data) {
        try {
          return JSON.parse(fs.readFileSync(`${env.dataFile}`, 'utf8'));
        } catch (error) {
          console.log(chalk.red(`Error encountered when parsing ${env.dataFile}:`), error.message);
          return data;
        }
      },

Adding the data files to the partials ensures the templates get rerendered/compiled.
I use fs.readFileSync to read an uncached version of the changed data file.

I might remove the entry from partials and try to accomplish it with just BrowserSync. But I couldn't find a way to recompile them yet.

@sagold
Copy link
Owner

sagold commented Sep 16, 2017

Yes it is. The watch on the json-file is a wanted features. I gladly add it, but cannot tell when.

Regards.
sagold

@sagold sagold added the feature feature request to implement label Sep 16, 2017
@sagold
Copy link
Owner

sagold commented Sep 16, 2017

This was quick: 6865e77. Added and published with v1.3.0. Just add an absolute filepath instead of an object to the data-property.

Does it work?

@sagold sagold closed this as completed Dec 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature feature request to implement
Projects
None yet
Development

No branches or pull requests

2 participants