This TemplateEngine is a Java port with optimizations of the original PHPLib TemplateEngine.



  • unsetVar() has been added to allow to remove template variables.

  • JUnit 5 tests have been added and improved with pitest.


  • The handling of unkown template variables has been changed to an enum instead of a string.

  • The substitution algorithm for variables in templates has been changed so that the variables will be first extracted from the template/block and only these will be replaced (instead of always looping over all known variables).

Usage example

final TemplateEngine engine = new TemplateEngine(HandleUndefined.comment);
/* final boolean successFile = */ engine.setFile("file2", new File("target/test-classes/templates/template2.tmpl")); //$NON-NLS-1$ //$NON-NLS-2$
/* String substResult = */ engine.subst("file2"); //$NON-NLS-1$
engine.setVar("variable1", "TEST1"); //$NON-NLS-1$ //$NON-NLS-2$
engine.setVar("variable2", "TEST2"); //$NON-NLS-1$ //$NON-NLS-2$
engine.setVar("variable3", "TEST3"); //$NON-NLS-1$ //$NON-NLS-2$
/* final boolean successBlock = */ engine.setBlock("file2", "BLK1", "BLK1_BLK"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
/* String parseResult = */ engine.parse("BLK1_BLK", "BLK1", false); //$NON-NLS-1$ //$NON-NLS-2$
/* String parseResult = */ engine.parse("BLK1_BLK", "BLK1", false); //$NON-NLS-1$ //$NON-NLS-2$

Known problems

TemplateEngine replacement order

There is a known and not fixable problem with this TemplateEngine.

Assuming the following template file and for test1, test3 a value has been set:

<!-- BEGIN test2 -->
{test1} {test3}
<!-- END test2 -->

Then after you did:

engine.setBlock("file3", "test2");

and make the final template parse:

engine.parse("output", "file3", false);

The result would be:

{test1} test3value

That’s because the engine iterates over the template variables in alpabetical order. This means that test1 will be replaced first, then test2 (block) will be replaced and makes the {test1} {test3} visible to the main template. After this test3 ist replaced. As you could see test3 from the block is replaced, because it is replaced later that test2 (block), while test1 is not replaced, because it was already replaced before the replacement of test2 (block).

This behaviour could be avoided when blocks always have names that are earlier in sort order than variable names (like using uppercase letters for blocks and lower case for variables).

Maven javadoc generation

The generation of javadoc’s failed during

mvn site

Please see Stackoverflow for more.

Maven site

The maven generated site could be found here TemplateEngine