I am trying to generate a unique JS file for each of a certain model in my app. I need a JS file specific to each "Campaign" entity. I am trying to do this with the following steps:
- Compile and minify JS asset with template tags in place of variables to replace later
- Use an http query to hit my application's API and retrieve the models, and
- Use a templating language to replace the variables and in the minified template and save to many JS files
Here is my code right now:
elixir((mix) => {
// Fetch all campaigns
axios.get('http://ift.tt/2lOaNPV', (response) => {
// For each campaign, read the template file
_.forEach(response, (campaign) => {
fs.readFile('resources/assets/js/tracking/templates/campaign-tracker.tmpl', 'utf8', (err, data) => {
// Replace template tags with model data
var compiled = _.template(data);
var output = compiled({ga_code: campaign.property_id});
// write output to public folder
fs.writeFile('public/js/campaigns/' + campaign.id + ".js", output, 'utf8', () => {
gutil.log('Completed '+campaign.name)
})
});
})
})
mix.sass('app.scss')
.webpack('app.js')
.webpack('tracking/pixel.js');
});
I've tried this a number of different ways... basically the issue seems to be that Elixir is not waiting for the asynchronous response from the API. Nothing inside the AJAX callback is being executed
I also wanted to get feedback on if there is a better template language to use than the basic _.template
that already integrates with , or a better way to read and write the templates and files than fs
.
My other thought for pulling this off would be to serve the JS from a route that dynamically generates it. So for instance campaigns/{campaign}/script.js
would serve a blade template that resulted in JS being returned. But if I do that, how would I turn JS into a blade file? I would need to write JS and then somehow turn it into a blade template for rendering. I also am worried that this would be a much slower loading page than a straight up JS file.
I think this also has applications in css, for instance if each user could configure CSS settings for the app and you wanted to generate a stylesheet per user. Thank you!
via Jeff