Jack Shultz
Jack Shultz

Reputation: 2081

How can grunt replace HTML elements?

I'm using grunt to copy markup from dust templates to JSP. I have many JSP pages where I want to replace the spans with localize classes with a spring tag

    <div class="push-right">
      <a href="/credentials/login">
      <span class="localize" name="top_bar.sign_in">Sign In</span>
      </a> |
      <a href="/credentials/register">
      <span class="localize" name="top_bar.register">Register</span>
      </a>
    </div>

So this block should become like this.

    <div class="push-right">
      <a href="/credentials/login">
        <spring:message code="top_bar.sign_in" />
      </a> |
      <a href="/credentials/register">
        <spring:message code="top_bar.register" />
      </a>
    </div>

UPDATE @Sam provided a good RegEx example that I am now following. I am constructing an object that I push to an array

var reLocalize = new RegExp('<span(?=[^>]*?class="localize").*?name="([^"]*).*?<\/span>', 'g');
localizeReplaceObject.match = reLocalize;
localizeReplaceObject.replacement = '<spring:message code=$1 />';
localizeReplaceArray.push(localizeReplaceObject);

then I run grunt replace

    replace: {
      localize: {
        options: {
          patterns: localizeReplaceArray
        }
        ,files: [
        {expand: true, flatten: true, src: ['../WEB-INF/views/index.jsp'], dest: '../WEB-INF/views/'}
        ]
    }

I run grunt again grunt replace:localize but the index.jsp localize tags don't update.

Running "replace:localize" (replace) task
Verifying property replace.localize exists in config...OK
Files: ../WEB-INF/views/index.jsp -> ../WEB-INF/views/index.jsp
Options: encoding="utf8", mode=false, processContentExclude=[], patterns=[{"match":{},"replacement":"<spring:message code=$1 />"}], excludeBuiltins=false, force
filePair src ../WEB-INF/views/index.jsp
Reading ../WEB-INF/views/index.jsp...OK
Processing source...Replace ../WEB-INF/views/index.jsp → ../WEB-INF/views/index.jsp
OK
Writing ../WEB-INF/views/index.jsp...OK

Done, without errors.

Upvotes: 1

Views: 614

Answers (1)

Sam
Sam

Reputation: 20486

Use a tool like grunt-replace (thanks, @Pinal) with the following expression to match span elements with class="localize" and capture the name attribute:

<span(?=[^>]*?class="localize").*?name="([^"]*).*?<\/span>

Demo

Upvotes: 2

Related Questions