[ Home | About | Syntax | Examples | Unit Tests | License ]
Here is an example view where the result differs if there is zero, one, or many items.
<view name="foo.bar">
<div class="items">
<h3><%= data.title %></h3>
<if test="!data.items || data.items.length === 0">
<call view="foo.warning" data="data">
<part name="messageArea">
<p class="item empty"><%= data.title %> contains no items.</p>
</part>
</call>
<else if="data.items.length === 1">
<p class="item">
<b><%= data.items[0].name %></b> is <i><%= data.items[0].detail %></i>
</p>
<else>
<ul><for each="data.items">
<li class="item">
<b><%= data.name %></b> is <i><%= data.detail %></i>
</li>
</for></ul>
</if>
</div>
To invoke this view from JavaScript, call the view as a function:
var data = {
title: "Hello world!",
items: [
{ name: "One", detail: 101 },
{ name: "two", detail: 2.718 }
]
};
// either get a string as output...
var markup = foo.bar(data).toString();
document.getElementById("baz").innerHTML = markup;
// ...or get DOM objects as output
var result = foo.bar(data).toDOM();
document.getElementById("baz").appendChild(result);
Which would output:
<div class="items">
<h3>Hello world!</h3>
<ul>
<li class="item">
<b>One</b> is <i>101</i>
</li>
<li class="item">
<b>Two</b> is <i>2.718</i>
</li>
</ul>
</div>
To invoke that same view from within Java, instantiate the view and call its render method. Here is a simple Servlet-as-controller example:
public class FooServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
DuelView view = new foo.bar();
// can use helper methods to declaratively construct view data graph
// or can directly use POJO/JavaBean types
Object data = DuelData.asMap(
"title", "Hello world!",
"items", DuelData.asList(
DuelData.asMap(
"name", "One",
"detail", 101),
DuelData.asMap(
"name", "Two",
"detail", 2.718)
));
// response headers
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
// response body
view.render(response.getWriter(), data);
}
}
DUEL views can be used to implement an MVC architecture in a JAX-RS (JSR-311) implementation (e.g. Jersey, JBoss RESTeasy, or Apache CXF).
The JAX-RS resource acts as the controller which produces different content (XML, JSON or a DUEL view) using MIME-type negotiation.
ViewResult
is a lightweight adapter between DuelView
and StreamingOutput
.
import javax.ws.rs.*;
import org.duelengine.duel.rs.ViewResult;
@Path("/orders")
public class OrdersController {
@GET
@Path("{id : \\d+}")
@Produces("application/json")
public Order getOrderJSON(@PathParam("id") long id) {
return findOrder(id);
}
@GET
@Path("{id : \\d+}")
@Produces("application/xml")
public Order getOrderXML(@PathParam("id") long id) {
return findOrder(id);
}
@GET
@Path("{id : \\d+}")
@Produces("text/html")
public ViewResult getOrderView(@PathParam("id") long id) {
Order orderData = findOrder(id);
return new ViewResult(SingleOrderView.class).data(orderData);
}
// ...
}