Insert id's into script tags using grunt - gruntjs

I want to insert id into the script tag
gruntfile.js
var obj = ['id1', 'id2', 'id3'];
var i = 0;
grunt.initConfig({
concat:{
basic:{
options:{
banner:'<script type="text/ng-template" id=' +obj[i] + ' >',
separator:'</script><script type="text/ng-template" id=' + obj[i++] + ' >',
footer:'</script>'
},
files:[{
src:['./src/folder/*.html'],
dest:'./src/foler/index.ftl'
}]
}
}
})
but on the output when the files are concated into index.ftl all the ids have the same id='id3'
how can I get the final concatinated file with all unique ids.

The following link solves the part of this question of adding ID,
I had created my own wrap plugin and used it in the code to added id's dynamically,
Replace all the text with specified replacement using grunt replace

Related

express-handlebars unable to print Object content ,

express-handlebars
exports.All_category = async (req,res)=>{
var categories = await Category.find({},{"date":0, '__v':0})
.then(result=> {
console.log(result);
res.render('category', { title: 'Category', cate: 'active',result });
})
I want to Print only name and id but its printing full Objects
You are printing the whole object because the model.find({}); method returns an object to result which you print afterwards.
So if you want to only print the id and the name then you should instead write:
console.log('Id: ' + result._id + ' Name: ' + result.name);
TO add run time option in handle bar engine
app.engine('hbs', exphbs({layoutsDir: __dirname + '/views/layouts', extname: 'hbs',
defaultLayout:'layout'}));
the above mentions app engine that i created first then i added some runtime options
like this
app.engine('hbs', exphbs({layoutsDir: __dirname + '/views/layouts', extname: 'hbs',
defaultLayout:'layout',
runtimeOptions: {
allowProtoPropertiesByDefault: true,
allowProtoMethodsByDefault: true
}}));

Replace string in a single file using gulp

I’m using a single task to generate css files from sass plus strip comments, create a source map and minify. I'm trying to replace a string in theme.components-md.scss file.
Here’s my attempt:
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
sourceMaps = require('gulp-sourcemaps'),
minifyCss = require('gulp-minify-css'),
replace = require('gulp-replace'),
filter = require('gulp-filter');
gulp.task('vendor:css', function() {
var themeComponentsFilter = filter('theme.components-md.scss');
return sass('resources/assets/sass/')
.pipe(stripComments({
safe: false
}))
.pipe(themeComponentsFilter)
.pipe(replace(/..\/img\//g, '../../img/vendor/'))
.pipe(themeComponentsFilter.restore())
.pipe(sourceMaps.init())
.pipe(minifyCss())
.pipe(sourceMaps.write('/', {
sourceMappingURLPrefix: 'http://core.dev/css/vendor'
}))
.pipe(gulp.dest('public/css/vendor'));
});
But it's not working.
Instead of filtering theme.components-md.scss, I had to filter for theme.components-md.css.

It is possible to compile less file to less with compression and without comments?

i have much more less files that are imported in a main.less file. Now i wanna to make a main.min.less file with imported files and compressed and without any comments. what command i used is:
lessc main.less > main.min.less -x
This command compress the file but can't remove the restricted comments(/*! comments */).
Keep in mind i wanna to make another .less file and not .css file. Any idea?
Because of Less code is very similar to CSS code, you should be able to (re)use many methods of for instance clean-css.
Create a file called clean-less and write down the following content into it:
#!/usr/bin/env node
var path = require('path'),
CommentsProcessor = require('clean-css/lib/text/comments'),
fs = require('fs');
var args = process.argv.slice(1);
var input = args[1];
if (input && input != '-') {
input = path.resolve(process.cwd(), input);
}
var parseFile = function (e, data) {
var lineBreak = process.platform == 'win32' ? '\r\n' : '\n';
var commentsProcessor = new CommentsProcessor(0,false,lineBreak);
//single line comments
var regex = /\/\/ .*/;
data = data.replace(/\/{2,}.*/g,"");
/*
methods from clean css, see https://github.com/jakubpawlowicz/clean-css/
*/
var replace = function() {
if (typeof arguments[0] == 'function')
arguments[0]();
else
data = data.replace.apply(data, arguments);
};
//multi line comments
replace(function escapeComments() {
data = commentsProcessor.escape(data);
});
// whitespace inside attribute selectors brackets
replace(/\[([^\]]+)\]/g, function(match) {
return match.replace(/\s/g, '');
});
// line breaks
replace(/[\r]?\n/g, ' ');
// multiple whitespace
replace(/[\t ]+/g, ' ');
// multiple semicolons (with optional whitespace)
replace(/;[ ]?;+/g, ';');
// multiple line breaks to one
replace(/ (?:\r\n|\n)/g, lineBreak);
replace(/(?:\r\n|\n)+/g, lineBreak);
// remove spaces around selectors
replace(/ ([+~>]) /g, '$1');
// remove extra spaces inside content
replace(/([!\(\{\}:;=,\n]) /g, '$1');
replace(/ ([!\)\{\};=,\n])/g, '$1');
replace(/(?:\r\n|\n)\}/g, '}');
replace(/([\{;,])(?:\r\n|\n)/g, '$1');
replace(/ :([^\{\};]+)([;}])/g, ':$1$2');
process.stdout.write(data);
}
if (input != '-') {
fs.readFile(input, 'utf8', parseFile);
}
Than make the clean-less file executable on your system (chmod +x clean-css).
You should probably also run npm install path and npm install css. After that you should be able to run:
./cleanless input.less > input-clean.less
The input-clean.less file will be some kind of minimized and not contain comments any more.
In the comments #seven-phases-max wonders if minifying reduces client side compile time. Well the client side compiler loads the Less files over a XMLHttpRequest. Reduce the number of bytes will give faster loading. I can not say that is a bottleneck or not.
When i try the above code with the navbar.less file from Bootstrap i found:
8.0K navbar-clean.less
16K navbar.less

JqxWidgets: Export nested grid

While working with JqxWidges I met a problem with exporting nested grids which use one JSON as a source file. The common solution doesn't work. Actually it exports only parent grid colums.
$("#excelExport").click(function () {
$("#jqxGrid").jqxGrid('exportdata', 'csv', chartName + ' ' + date);
});
One of the existing solutions (http://www.jqwidgets.com/community/reply/reply-to-export-data-from-a-nested-grid-13/) propose to push nested rows into data array while calling initrowdetails function.
Yes it works! But only for nested grids and in case when this grid was selected.
So, from this step I am moving to next aproach:
To collect all necessary data into array using initial JSON (prevent you from gathering only separate selected data);
To initialise parent grid columns with all existing data and mark nested columns as hidden. Then when export don't forget to add true parameter to export both non/hidden columns;
Use standard export with custom array parameter;
That's it!
Data collecting:
var toExport = data.allClientsCountChart;
var exp = new Array();
for(var i in toExport){
var client = {};
var countr = toExport[i].countries;
client[labels.clientType]=toExport[i].clientType;
client[labels.clientTypeCount]=toExport[i].clientTypeCount;
exp.push(client);
for(var j in countr) {
var country = {}
var detailes = countr[j].clientDetails;
country[labels.countryType]=countr[j].countryType;
country[labels.clientsNumber]=countr[j].clientsNumber;
exp.push(country);
for(var d in detailes) {
var det = {}
det[labels.scriptName]=detailes[d].scriptName;
det[labels.clientsCount]=detailes[d].clientsCount;
exp.push(det);
}
}
}
Export:
$("#excelExport").click(function () {
$("#jqxGrid").jqxGrid('exportdata', 'csv', chartName + ' ' + date, true, exp, true);
}
And don't forget to set the fifth pafameter into true to export hidden columns.
No doubds, it looks hardcoded. But it works for me.
So, if you have a good solution - please leave a comment!!!

Grunt task for making sure you have copyrights on each file

I need to make sure there's copyrights notice at the beginning of each file.
How can I use grunt to fail my build in case the copyrights statement is missing?
First of all, I'm assuming you are referring to *.js or *.html or other similar work files, and not to graphic or binary files.
This can be done, with a grunt.registerTask which will:
1. loop through all relevant files
2. Read and compare first line to copyright line
3. If different - re-write file but a new first line which will be the copyright info
Pretty simple. Again - this will not work on binary files. I wrote this for you but it seems very useful, I might consider adding it as a plugin. Field tested:
run it by grunt verifyCopyright and also make sure that if your files are in a different directory your change it, and also if you want to process other files add them to the list as well. good luck...
grunt.registerTask('verifyCopyright', function () {
var fileRead, firstLine, counter = 0, fileExtension, commentWrapper;
copyrightInfo = 'Copyright by Gilad Peleg #2013';
//get file extension regex
var re = /(?:\.([^.]+))?$/;
grunt.log.writeln();
// read all subdirectories from your modules folder
grunt.file.expand(
{filter: 'isFile', cwd: 'public/'},
["**/*.js", ['**/*.html']])
.forEach(function (dir) {
fileRead = grunt.file.read('public/' + dir).split('\n');
firstLine = fileRead[0];
if (firstLine.indexOf(copyrightInfo > -1)) {
counter++;
grunt.log.write(dir);
grunt.log.writeln(" -->doesn't have copyright. Writing it.");
//need to be careful about:
//what kind of comment we can add to each type of file. i.e /* <text> */ to js
fileExtension = re.exec(dir)[1];
switch (fileExtension) {
case 'js':
commentWrapper = '/* ' + copyrightInfo + ' */';
break;
case 'html':
commentWrapper = '<!-- ' + copyrightInfo + ' //-->';
break;
default:
commentWrapper = null;
grunt.log.writeln('file extension not recognized');
break;
}
if (commentWrapper) {
fileRead.unshift(commentWrapper);
fileRead = fileRead.join('\n');
grunt.file.write( 'public/' + dir, fileRead);
}
}
});
grunt.log.ok('Found', counter, 'files without copyright');
})
Instead of checking to see if it's there and failing, why not just have a task that automatically injects it? See grunt-banner.
https://github.com/thekua/grunt-regex-check could be what you want. You define the regex to check for and if it finds it then the task fails.

Resources