Escaping an Issue with Grunt "string-replace"
published on
Since I started using Grunt, I have found more and more cases where Grunt tasks turn out to be very useful and a huge timesaver. That is, timesaver once you got whatever you’re trying to do up and running. In the most recent case, I ran into an issue with using Grunt string-replace to replace background-image URLs in my CSS file with a different path to prepare them for use with Rails" asset pipeline.
I needed to search for : url(img/imagename)
to then be replaced with : url(<%= asset_path 'img/imagename' %>)
.
As the first replacement pattern I used ':$1url(<%= asset_path \'$2$3\' %>)’
. This failed with an error message. Since I was using the < & > characters in the pattern, I figured these characters might need to be escaped.
I tried ':$1url(\<%= asset_path \'$2$3\' %\>)’
and various variations, all without any luck. Eventually I found a hint on Stack Overflow, that this might not work this way at all and needs to be processed with two passes.
After checking back with the author of string-replace, this problem seems to be related to Lo-Dash's template security.
The final working code looks like this now and works pretty much as well as it would with running it in one pass, I believe.
'string-replace': {
inline: {
files: {
'dist/css/app.css.erb': ['css/app.css'],
},
options: {
replacements: [{
pattern: /:(\s*)url\((img)(.+?)\)/ig,
replacement: ':$1url(\<%= asset_path \'$2$3\' CLOSETAG)'
},
{
pattern: /CLOSETAG/g,
replacement: '%>'
}]
}
}
}