Question

I'm looking for a web template engine (any language, Java prefered) that compiles template files before runtime. It should detect unknown property names and routes in my template. For example:

<h1>{{hello}}</h1> 

should give a compile error, if there is no corresponding field on the model that I render.

Was it helpful?

Solution 2

I recommend you to take a look Rythm template engine. Rythm is a static typed template engine for Java. You need to declare all the template parameters using @args directive. And the consequence is you get a type safe template with clear interface.

You can play with the online interactive fiddle site for Rythm at http://fiddle.rythmengine.org/

Disclaim: I am the author of Rythm template engine

Updates to answer @user2043423's concern about attribute checking

So first every rythm template is compiled into a java class, thus it's absolutely typesafe. second, because it is typesafe, it does check if the attributes exists in your Java class or not. For example you have a rythm template defined as:

@args Employee employee

Hello @employee.getFistName()

You will get a compilation error when you run the template because there is a typo in @employee.getFistName(), and once you fixed that to @employee.getFirstName() the rythm will go ahead to render the template

In case you want to check if the template argument employee has been passed to the template or not, use @if:

@args Employee employee

@ifNot(employee) {
    @return
}

Hello @employee.getFirstName()!

See http://rythmengine.org/doc/directive.md#if for more about @if directive

OTHER TIPS

I've implemented static-mustache library to provide a type-safe template engine based on mustache syntax, like the one in your question.

It checks both syntax errors and type-errors (like missing property) at compile-time. It requires zero build configuration as it's a standard annotation processor.

Templates remain pure mustache templates with all type-information extracted from normal Java-class used for rendering.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top