TinyTemplate is a small single-file templating engine in Java with no dependencies. A PHP version is also available.
License: GPLv3
You can download TinyTemplate from Sourceforge.
You can also download the current development versions directly from the code repository.
Java: copy net/sf/tinytemplate/Template.java to your source directory.
PHP: copy tinytemplate.php to your website.
Java:
... include java.util.Map; include net.sf.tinytemplate.Template; ... String template = ... Map<String,Object> variables = ... String text = new Template(template).process(variables); ...
You can use the static helper functions to load the template string:
... // from a URL String template1 = Template.from(new URL("http://localhost/index.html")); // from a resource URL String template2 = Template.from(this.getClass().getResource('/index.html')); // from a resource stream String template3 = Template.from(this.getClass().getResourceAsStream('/index.html'), 'UTF-8'); // from a file String template4 = Template.from(new File("/var/www/index.template")); ...
PHP:
... require_once('tinytemplate.php'); ... $template = ... $variables = array(...); $t = new Template($template); $text = $t->process($variables); ...
Conditions:
{{if value}} ... {{else}} ... {{end}} {{if ! value}} ... {{else}} ... {{end}} {{if value1 == value2}} ... {{else}} ... {{end}} {{if value1 != value2}} ... {{else}} ... {{end}} {{if value1 <= value2}} ... {{else}} ... {{end}} {{if value1 >= value2}} ... {{else}} ... {{end}} {{if value1 < value2}} ... {{else}} ... {{end}} {{if value1 > value2}} ... {{else}} ... {{end}}
The else is optional.
The first two conditions return true, if the value is not empty (null, empty string, empty array/map/list) or empty, respectively.
Loops:
{{foreach var in value}} ... {{end}}
The value must be an array, collection, map or iterable, var is a variable name, which can be used within the loop.
Output values:
{{value}} {{value defaultvalue}} {{value defaultvalue formatvalue}}
This outputs the value. If the value is null/empty, the defaultvalue is output. If the value is a number or date and a formatvalue is given, the value is formatted (currently only in Java, formatting see DecimalFormat and SimpleDateFormat).
Values:
Values can be literals or variables, even nested variables, e.g.
TinyTemplate is easily extensible by extending the class.
Override boolean processCondition(Map
Override Pattern getTagPattern(), depending on the format also String getTagName(Matcher m) and String[] getTagParams(Matcher m).
Create new implementations of Part and override Part parseTag(String template, Matcher m) returning these new Parts.
Override String format(Object object, String format).
TinyTemplate