gulp-swig
gulp-swig copied to clipboard
Common JSON data
Hi guys, I have an issue here, I can't actually add some global data that's common for all the templates. I've tried a solution offered on stackoverflow, but it didn't worked for me. I'm getting an error as it couldn't find the module 'src/data/global.json'.
This is my config object:
var swigConfig = {
load_json: true,
defaults:{
cache: false
},
json_path: 'src/data/'
};
And this is my gulp task:
return gulp.src('src/*.html').
pipe(swig(swigConfig)).
pipe(gulp.dest('build/'))
I would like to achieve something like this within my templates:
{{ global.someData }}
Thank you in advance
My bet is that you're not passing the path to global.json correctly. You can verify that by using fs.realpath
to see if the path is correct. Something like console.log(fs.realpathSync('src/data/global.json')
Other than that, I recommend passing data to swig templates using another plugin I created a while ago to clean this process up. Give gulp-data
a try. https://www.npmjs.com/package/gulp-data
Thank you so much @colynb for your answer, I'm actually new to Node and Gulp so may be i'm missing something, I've tried to use your gulp-data plugin and it works pretty well with just a small fix, by adding a second parameter to the basename function
return gulp.src('src/*.html').
pipe(data(function(file) {
return require('./src/data/' + path.basename(file.path, '.html') + '.json');
})).
pipe(swig(swigConfig)).
pipe(gulp.dest('build/'));
As I suppose, it should be adding a '.json' file for each '.html' file that it finds, but how can I add some additional '.json' files, independent from '.html' files (by using gulp-data I really do like the concept). Sorry if my question is kind elementary.
Thank you.