gulp-file-include
gulp-file-include copied to clipboard
@@include referencing a json file
Why can't I use a json file with a @@include
tag? When I pass the json context, the @@include
tag works fine, but if I specify a json file, nothing happens: no error and no binding.
I'm sure the json file exists and its well referenced because replacing the @@include
tag for @@loop
leads to include the same template file several times (once per json property - which means that a loop statement have been aplied using my json structure). I'm using this json in several templates, so I really need to include it by referencing its file.
My goal is do something like that:
@@include('partials/_gallery-before.html', '../json/data.json')
@@loop('partials/_gallery-item.html', '../json/data-gallery.json')
@@include('partials/_gallery-after.html', '../json/data.json')
I found two possible workarounds, but they are very bad practices, I guess. The first one is define my data.json
as an array with just one position containing my real object, what gives me this code:
@@loop('partials/_gallery-before.html', '../json/data-as-array.json')
@@loop('partials/_gallery-item.html', '../json/data-gallery.json')
@@loop('partials/_gallery-after.html', '../json/data-as-array.json')
The downside is I need to use [0]
in other places, because I use the same json
in my js
files.
The second choice, that I'm using now (don't blame, please) is use gulp-include
to add my json file as a literal json. I run the gulp-include
first so then I run the gulp-file-include
and my template look like this:
@@include('partials/_gallery-before.html', //=include ../json/data.json)
@@loop('partials/_gallery-item.html', '../json/data-gallery.json')
@@include('partials/_gallery-after.html', //=include ../json/data.json)
Ok. I know, I know. So I'm here to found a better solution just like I said it was my goal. :)
@robsonrosa Did you find a better solution for this?
Sorry, @dnnsldr, but I couldn't find a better solution.
Did you find a solution for this? could you give me the code you said "two possible workarounds, but they are very bad practices" . I do not understand well
This is not supported and its very weird.
Here is the solution everyone.
function requireUncached(module) {
delete require.cache[require.resolve(module)]
return require(module)
}
// Boom boom
if (args[3]) {
var includeJSON = JSON.parse(args[3]);
if ("file" in includeJSON) {
var datafile = includeJSON.file;
var jsonfile = file.base + datafile.replace(/^('|")/, '').replace(/('|")$/, '')
// check if json file exists
if (fs.existsSync(jsonfile)) {
args[3] = JSON.stringify(requireUncached(jsonfile));
} else {
return console.error('JSON file not exists:', jsonfile)
}
}
}
Put this in index.js
before line 175.
I've this issue https://github.com/haoxins/gulp-file-include/issues/167