Fork this page on GitHub

Scuery

Transform HTML using jQuery style DSL in Scala

Scuery

Scuery provides an XML transformation library which uses a jQuery style approach, using CSS3 selectors to transform HTML or XHTML to inject dynamic information from static HTML/XHTML documents owned by designers.

For example a designer could create a mock up layout in HTML; or have a sample page with mock data. Scuery can then be used to transform the XML, using Scala's NodeSeq with CSS3 selectors.

Simple Example

If you had the following HTML…

<div id="content">
  <table class="people">
    <tr>
      <th>Name</th>
      <th>Location</th>
    </tr>
    <tr>
      <td class="name">DummyName</td>
      <td class="location">DummyLocation</td>
    </tr>
  </table>
</div>

Then you can transform this with the following code.

object transformer extends Transformer {
  $("table .name").contents = "Hiram"
  $(".location").contents = "Tampa"
}

val result = transformer(xml)

We are creating an object, transformer, which we can then use as a function to transform XML.

More complex example

Typically you want to iterate through collections so something like this…

<div id="content">
  <table class="people">
    <tr>
      <th>Name</th>
      <th>Location</th>
    </tr>
    <tr class="person">
      <td class="name">DummyName</td>
      <td class="location">DummyLocation</td>
    </tr>
  </table>
</div>

There's the Scala code to create the transformer…

// add an implicit conversion from Transform -> NodeSeq
import org.fusesource.scalate.scuery.Transform._

val people = List(Person("James", "Mells"), 
                  Person("Hiram", "Tampa"))

object transformer extends Transformer {
  $(".person") { node =>
    people.flatMap { p =>
      new Transform(node) {
        $(".name").contents = p.name
        $(".location").contents = p.location
      }
    }
  }
}

Which would generate

<div id="content">
  <table class="people">
    <tr>
      <th>Name</th>
      <th>Location</th>
    </tr>
    <tr class="person">
      <td class="name">James</td>
      <td class="location">Mells</td>
    </tr>
    <tr class="person">
      <td class="name">Hiram</td>
      <td class="location">Tampa</td>
    </tr>
  </table>
</div>