outaTiME/grunt-replace

passing regex var to grunt.file.read()

markusfalk opened this issue · 5 comments

I have the following:

<div class="col">
  {{article}}
</div> <!-- col -->
...
  patterns: [
    {
      match: /{{(.+)}}/,
      replacement: '<%= grunt.file.read("elements/$1.html") %>'
    }
  ]
...

I would like to pass the first variable from the regex into the read() to get a file with the name of the placeholder. So I would expect the placeholder to be replaced with elements/article.html

Instead I get the following error:

Unable to read "elements/$1.html"

Any idea what the problem could be?

Thanks alot.

Hi pal,

you could try, because grunt template processed before replace happens ...

...
  patterns: [
    {
      match: /{{(.+)}}/,
      replacement: function (match, p1) {
        return grunt.file.read("elements/" + p1 + ".html");
    }
  ]
...

please ... tell me if it works !!!

Thanks. It does what I wanted but it only matches one occurence. I should have noted that I have many different placeholders:

<header>
    {{nav}}
</header>
<div class="col">
  {{article}}
</div> <!-- col -->

I want all placeholders to be replaced with matching html files :)

yup, no problem ... what happen if change the matching regex with global flag ...

...
  patterns: [
    {
      match: /{{(.+)}}/g,
      replacement: function (match, p1) {
        return grunt.file.read("elements/" + p1 + ".html");
    }
  ]
...

it might be work 👍

news about that ??

working great. Could have thought about that myself though. Thanks alot! 👍