• Skip to primary navigation
  • Skip to main content
  • Skip to footer

JH Tech Services

A knowledgebase

  • Portfolio
  • Knowledgebase
  • About

Grunt task to add table attributes for an email campaign

September 26, 2015 by jer0dh

So far I haven’t seen if these attributes on a table actually help in making the html email more compatible with email clients. My tests on Email On Acid don’t show any difference that I can see, but sometimes I just want to make sure. I don’t want to clutter up my source html file with these attributes but wouldn’t mind having them automatically added. A grunt task fits the bill. This task will read the source file and produce an output file where the table attributes border, cellspacing, and cellpadding are added if they are not already there.

I want to go from this:


 

to this


 

This Gruntjs task will do this for us.


	grunt.registerMultiTask('tableAttrib', 'Checks table tags to add default border, cellpadding, etc', function() {
		var data=this.data;
		src = grunt.file.read(data.src);
		var count = 0, border= 0, cellspacing= 0, cellpadding=0;
		var content = src.replace(//gm, function(match,p1){
			if (p1.match(/border=/i) == null) {
				p1 += ' border="0"';
				border += 1;
			}
			if (p1.match(/cellspacing=/i)== null) {
				p1 += ' cellspacing="0"';
				cellspacing += 1;
			}
			if (p1.match(/cellpadding=/i) == null) {
				p1 += ' cellpadding="0"';
				cellpadding += 1;
			}
			count += 1;
			return '';
		});
		grunt.file.write(data.dest, content);
		grunt.log.writeln(count + ' tables found. '+ border +' border added. '+ cellpadding + ' cellpadding added. ' + cellspacing + ' cellspacing added. File "' + data.dest + '" created.');
	});

That’s it. I nice time saver for me. Hope it can help someone else doing these crazy HTML emails.

I have a gitHub repo with a grunt environment for email campaigns. I haven’t added this yet, but it might be there when you read this.

  • HTML
  • JavaScript
  • Knowledgebase

Footer

  • Portfolio
  • Knowledgebase
  • About

© 2023