Chunk是我的免費開源Java模板引擎。 Chunk就像Freemarker或Velocity,但語法更直觀。
組塊的嵌套的 「循環」 和 「如果」 的標記,使這種事情非常簡單:
my_template.chtml(發生在類路徑,例如,在SRC /主題/ my_template.chtml)
<html>
<head>
</head>
<body>
<table>
<tbody>
<thead>
Blah Blah table Header--Constant Part
</thead>
<tr>
some text-constant part
</tr>
{!---Main Customization Part--}
{% loop in $list as $row %}
<tr>
{% loop in $row as $cell %}
{% if ($cell.color == "blue") %}
<td class="{$class_a}">{$cell.text}</td>
{% else %}
<td class="{$class_b}">{$cell.text}</td>
{% endif %}
{% endloop %}
</tr>
{% endloop %}
</tbody>
</table>
</body>
</html>
樣本Java與此模板的工作:
import com.x5.template.Theme;
import com.x5.template.Chunk;
...
Theme theme = new Theme();
Chunk html = theme.makeChunk("my_template");
html.set("class_a", "blue_cell");
html.set("class_b", "plain_cell");
String row1 = "[[color,text],[blue,moe],[red,curly],[orange,larry]]";
String row2 = "[[color,text],[red,hat],[black,dog],[blue,bottle]]";
String[] list = new String[]{row1,row2};
html.set("list", list);
out = getOutputWriter();
html.render(out); // or System.out.print(html.toString())
out.flush();
out.close();
我使用內聯表(一大塊方便的格式),以創建循環型數據,但你可以使用任何物品T的數組或列表帽子實現com.x5.util.DataCapsule和Chunk將在渲染模板之前將數據從對象中複製出來。
最終輸出:
<html>
<head>
</head>
<body>
<table>
<tbody>
<thead>
Blah Blah table Header--Constant Part
</thead>
<tr>
some text-constant part
</tr>
<tr>
<td class="blue_cell">moe</td>
<td class="plain_cell">curly</td>
<td class="plain_cell">larry</td>
</tr>
<tr>
<td class="plain_cell">hat</td>
<td class="plain_cell">dog</td>
<td class="blue_cell">bottle</td>
</tr>
</tbody>
</table>
</body>
</html>
你有沒有簽出「gagawa」? http://code.google.com/p/gagawa/ – 2012-03-28 14:42:52
您可以使用簡單的模板引擎。檢查此條目:http://stackoverflow.com/questions/3793880/lightweight-template-engine-in-java – mdakin 2012-03-28 14:43:10
*「我想得到低於輸出。」*該輸出格式不正確。使用[驗證服務](http://validator.w3.org/)進行檢查。 – 2012-03-28 14:44:01