Clone wiki

duel / Examples

DUEL Examples

View Source

Here is an example view where the result differs if there is zero, one, or many items.

<view name="">

<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>

	<else if="data.items.length === 1">
		<p class="item">
			<b><%= data.items[0].name %></b> is <i><%= data.items[0].detail %></i>

		<ul><for each="data.items">
			<li class="item">
				<b><%= %></b> is <i><%= data.detail %></i>

Client-Side Views

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 =;
document.getElementById("baz").innerHTML = markup;

// ...or get DOM objects as output
var result =;

Which would output:

<div class="items">
	<h3>Hello world!</h3>

		<li class="item">
			<b>One</b> is <i>101</i>
		<li class="item">
			<b>Two</b> is <i>2.718</i>

Server-Side Views

Servlet-based Controller

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;

		// 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(
					"name", "One",
					"detail", 101),
					"name", "Two",
					"detail", 2.718)

		// response headers

		// 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.


public class OrdersController {

	@Path("{id : \\d+}")
	public Order getOrderJSON(@PathParam("id") long id) {
		return findOrder(id);

	@Path("{id : \\d+}")
	public Order getOrderXML(@PathParam("id") long id) {
		return findOrder(id);

	@Path("{id : \\d+}")
	public ViewResult getOrderView(@PathParam("id") long id) {
		Order orderData = findOrder(id);
		return new ViewResult(SingleOrderView.class).data(orderData);

	// ...