不会发出语法错误的简单模板语言

Gel*_*ler 3 java syntax templates

我正在寻找一个不会发出语法错误的简单模板引擎。我的意思是,根据定义,每个模板都应该具有有效的语法。如果无法解析变量或代码构造,它应该简单地打印出损坏的代码,而不是中止渲染。

我想这样做的原因是因为我想在高级用户可以调整自己的模板的环境中使用它们,但我很难将错误传达给他们。

现在,我正在使用一些高级搜索和替换标记,效果很好,但不支持循环和 if 语句。我想要一个简单的模板语言,允许非常简单的 if 和循环语句。

你知道有什么模板引擎可以在 Java 中做到这一点吗?

实施例A

模板:

My template <h1>{title}</h1>
<p>{message}</p>
<ul>
{foreach items as item}
<li>{item.value}</li>
{/foreach}
</ul> 
Run Code Online (Sandbox Code Playgroud)

数据:

{
    "title": "Hello World",
    "items": [
        {
            "value": "foo"
        },
        {
            "value": "bar"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

结果:

My template <h1>Hello World</h1>
<p>{message}</p>
<ul>
    <li>foo</li>
    <li>bar</li>
</ul> 
Run Code Online (Sandbox Code Playgroud)

实施例B

模板:

My template <h1>{title}</h1>
<p>{message}</p>
<ul>
{foreach items
<li>{item.value</li>
{/foreach}
</ul> 
Run Code Online (Sandbox Code Playgroud)

数据:

{
    "title": "Hello World",
    "message": "Test",
    "items": [
        {
            "value": "foo"
        },
        {
            "value": "bar"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

结果:

My template <h1>Hello World</h1>
<p>Test</p>
<ul>
{foreach items
<li>{item.value</li>
{/foreach}
</ul>
Run Code Online (Sandbox Code Playgroud)

编辑:

我实际上编写了自己的简单模板引擎并且它有效。我选择类似 xml 的语法,其中 if 语句和循环始终命名。例如{for_cars}&{/for_cars}{if_loggedIn}&{/if_loggedIn}这使得修复错误变得更容易。但最终我选择了更简单的设计,我只是将模板拆分为多个较小的模板,并在代码中围绕模板实现循环和 if 语句。模板现在仅支持变量,但不支持逻辑。这样用户就有更少的出错选择,我认为这使得它成为一种更强大的用户设计。

dev*_*ock 5

The Apache Velocity Template engine can handle Example A - one or more parameters not specified when template is syntactically correct. The template will look like below in velocity:

My template <h1>${title}</h1>
<p>${message}</p>
<ul>
#foreach( $item in $items )
<li>${item.value}</li>
#end
</ul>
Run Code Online (Sandbox Code Playgroud)

And the output will be like below:

My template <h1>Hello World</h1>
<p>${message}</p>
<ul>
<li>foo</li>
<li>bar</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

But it wasn't able to parse the template when I removed the closing parenthesis from the foreach line. And I do agree with Konrad that, while a templating framework can be used to handle advanced templating, there might not be any framework that can selectively evaluate only the valid parts of a template and even if there is, communicating the errors back to the users might be the right thing to do