4. Templates

In order to separate the presentation and the data layer, RIFE uses templates. A template is a regular HTML file with specific markup to structure it for web application usage. There's no template scripting language and it's not possible to include any logic at all inside them. They only contain blocks and placeholders for content: values. The logic is placed in the elements where blocks are manipulated and content assigned or constructed in the placeholders. The blocks and value tags are replaced by the generated output before being sent to the browser.

This makes RIFE templates different from other solutions, for example JSP, since the pages can be edited in any regular HTML editor. Since the files are valid HTML, they can also easily be tried out in a browser without having to run the whole application.

In the Hello World example, all the content was generated directly in the Java class implementation, by writing it from the processElement method. It would be pretty cumbersome if all content would need to be generated in this fashion. It is here that templates come in handy.

In the numberguess application, there are two templates: one for the guess page and one for the success page. A quick look at the guess template gives the following snippet:

Example 3.6. The template for the guess page

<p>Guess a number from 0 to 100</p>
<!--V 'warning'--><!--/V-->
<!--B 'invalid'-->
<p><font color="#990000">The guess is invalid.</font></p>
<p><i><!--V 'indication'--><!--/V--></i></p>
<!--B 'lower'-->The answer is lower.<!--/B-->
<!--B 'higher'-->The answer is higher.<!--/B-->

As you can see, RIFE makes use of ordinary HTML comments. There is also another syntax for template tags, that is a bit less verbose where [! is used instead of <!-- and ] instead of -->. You can see the two tags V and B being used, where V is a placeholder for a value and B is the definition of a block. To insert a string into a value tag from the Java element code might look like this:

template.setValue("warning", "The answer is lower.");

In this example though, we use the blocks that are defined with B tags and insert one of them as the content of a value:

template.setBlock("warning", "lower");

This way we don't have to use one single string of HTML inside the Java code, and no logic in the templates. This very clear separation of content and logic is one of RIFE's great strengths.