Better template language needed [closed]

非 Y 不嫁゛ 提交于 2019-12-04 11:06:51

问题


Yes, I know that this has been asked before. But most of the questions were two years ago, and there's got to be a better answer today.

I need a template language for rendering HTML. Requirements:

  1. Must be callable from Java.

  2. Must not be Freemarker, Velocity, or StringTemplate. We've been using Freemarker for a year, and it's too slow. It consumes 50% of our CPU cycles under load. Velocity is worse than Freemarker, and StringTemplate has got its own issues.

  3. It must consume JSON, or its Java equivalent, i.e. Maps, Lists, and primitives.

I'm starting to get Node.js envy. There has been a ton of template activity for Javascript in the last year, but little for Java (that I know of).

The ideal language would look like Liquid, which exists only for Rails.

Jade exists for Java, but I don't want all the HTML reformatting that comes with it.

Update

I eventually settled on Handlebars, which is also available for Java. Both work great.


回答1:


Chunk is json-friendly. JSON can be used as a tag value in your controller code or in the templates themselves for exec/macro calls.

{% exec %}
  {% data @json %}
    { name: "whatever",
      vitals: ["an","array","of","data"],
      friends: [{name: "bob"},{name: "crystal"}]
    }
  {% enddata %}

  <div>Name: {$name}</div>

  {% if ($friends) %}
    <div>Friends:

      <ul>
      {% loop in $friends as $friend %}
        <li>{$friend.name}</li>
      {% endloop %}
      </ul>

    </div>
  {% endif %}

{% endexec %}

Or, just use the inner template and inject the json from the java side.

src/themes/example.chtml

  <div>Name: {$name}</div>

  {% if ($friends) %}
  <div>Friends:

    <ul>
    {% loop in $friends as $friend %}
     <li>{$friend.name}</li>
    {% endloop %}
    </ul>

  </div>
  {% endif %}

MyController.java

Theme theme = new Theme();
Chunk html = theme.makeChunk("example");

html.set("name", "whatever");
html.set("vitals", getJsonArray() );
html.set("friends", getJsonFriendObjects() );

html.render( out );

As long as the getJsonXXX() methods return something that implements List and Map, Chunk will glue it into the template correctly (even if those Lists and Maps nest more Lists and Maps).

Output:

<div>Name: whatever</div>

<div>Friends:

  <ul>
   <li>bob</li>
   <li>crystal</li>
  </ul>

</div>



回答2:


Java+ is a simple preprocessor solution. It just stringifies markup:

System.out.println({{
 <html>
  <body>
   ...
  </body>
</html>}})

It has configurable delimiters and passes through Java code rather than consuming it:

System.out.println({{
<xmlExample>
  <name>{{fpp}}</name>
  <number>{{bar}}</number>
</xmlExample>
}});

References

  • Java+ Preprocessor Release 2.0: Syntax


来源:https://stackoverflow.com/questions/10524352/better-template-language-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!