Following is an example of a template used when generating an HTML file that contains a variable list of tables each containing a variable list of rows:
<html> <head> #TEMPLATE(title) <title>#VAR(title)</title> #END </head> <body> #TEMPLATE(table) <table> <tr> <th>#VAR(head1)</th> <th>#VAR(head2)</th> </tr> #INCLUDE(row.html) </table> #END </body> </html> </code>The row template is specified in the included file:
#TEMPLATE(row) <tr> <td>#VAR(val1)</td> <td>#VAR(val2)</td> </tr> #END
A child template is generated from the text between the #TEMPLATE() and #END tags and is addressed using the template name specified between the brackets. The template name is used to lookup the template reference in the parent template. The tags for the root template are implied and the root template does not need a name.
Placeholders are specified using a #VAR() tag. The name of the placeholder specified in the brackets is used to lookup the placeholder reference in the parent template.
Files can be include using #INCLUDE(filename) and the semantic is as if the included content would be copied in the including file. The include mechanism does not automatically add a #TEMPLATE tag because the file included may not be a template.
package com.accendia.yawte.test; import com.accendia.yawte.TemplateManager; import com.accendia.yawte.Template; import com.accendia.yawte.Placeholder; import java.io.FileWriter; import java.io.IOException; public class YawteMain { public static void main(String[] args) { // Create a template manager that will load, parse and cache templates TemplateManager manager = new TemplateManager(null, false); Template mainTmpl = null; // Load the root template try { mainTmpl = manager.load( "templates/main.html" ); } catch( Exception ex ) { ex.printStackTrace(); System.exit(1); } // Get references to child templates and placeholders // that will be used to generate content Template tableTmpl = mainTmpl.getTemplate( "table" ); Placeholder head1 = tableTmpl.getPlaceholder( "head1" ); Placeholder head2 = tableTmpl.getPlaceholder( "head2" ); Template rowTmpl = tableTmpl.getTemplate( "row" ); Placeholder val1 = rowTmpl.getPlaceholder( "val1" ); Placeholder val2 = rowTmpl.getPlaceholder( "val2" ); // tables iterations for( int i=0; i<3; i++ ) { // set the values for the table header head1.setContent( "H1_" + i); head2.setContent( "H2_" + i); // rows iteration for( int j=0; j<10; j++ ) { // set values for table cells val1.setContent( "VAL_" + i + "-" + j ); val2.setContent( "VAL_" + i + "-" + j ); // generate the content for a row rowTmpl.generate(); } // generate the content for a table tableTmpl.generate(); } // generate the page content mainTmpl.generate(); // write the content of the root template to file try { FileWriter writer = new FileWriter("page.html"); mainTmpl.write( writer ); writer.close(); } catch( IOException ex ) { ex.printStackTrace(); System.exit(1); } } }