I'm looking for a simple template engine that does not emit syntax errors. What I mean by that is that every template by definition should have a valid syntax. If a variable or code construct can't be resolved it should simply print out the broken code instead of aborting rendering.
The reason I want to do that is because I want to use them in a context where power users can adjust their own templates but it is very difficult for me to communicate errors back to them.
Right now I'm using a bit of advanced search and replace for tokens which works great but doesn't support loops and if statements. I would like to have a simple template language that allows for very simple if and loop statements.
Do you know of any template engine that can do that in Java?
Example A
Template:
My template <h1>{title}</h1>
<p>{message}</p>
<ul>
{foreach items as item}
<li>{item.value}</li>
{/foreach}
</ul>
Data:
{
"title": "Hello World",
"items": [
{
"value": "foo"
},
{
"value": "bar"
}
]
}
Result:
My template <h1>Hello World</h1>
<p>{message}</p>
<ul>
<li>foo</li>
<li>bar</li>
</ul>
Example B
Template:
My template <h1>{title}</h1>
<p>{message}</p>
<ul>
{foreach items
<li>{item.value</li>
{/foreach}
</ul>
Data:
{
"title": "Hello World",
"message": "Test",
"items": [
{
"value": "foo"
},
{
"value": "bar"
}
]
}
Result:
My template <h1>Hello World</h1>
<p>Test</p>
<ul>
{foreach items
<li>{item.value</li>
{/foreach}
</ul>
Edit:
I actually wrote my own simple template engine and it worked. I choose a xml like syntax where if statements and loops where always named. For example {for_cars} & {/for_cars} and {if_loggedIn} & {/if_loggedIn} which made it easier to repair errors. But in the end I opted to go for a simpler design where I simply split the template into multiple smaller templates and implementing the loops and if statements around the templates in code. The templates now only support variables but no logic. That way users have fewer options to go wrong which I think makes it a way more robust user design.