我正在实现一些指令来根据某些自定义标记呈现内容。我希望 Freemarker 源代码可读,因此我希望在模板源代码的模板正文中自由使用空格和换行符,但在实际渲染它们时希望抑制所有这些内容。示例:
考虑表的 FreeMarker 源:
<@table args={"border": 1}>
<@tr>
<@td>table_data_with_no_line_breaks_r1c1</@td>
<@td>table_data_with_no_line_breaks_r1c2</@td>
<@td>table_data_with_no_line_breaks_r1c3</@td>
</@tr>
<@tr>
<@td>table_data_with_no_line_breaks_r2c1</@td>
<@td>table_data_with_no_line_breaks_r2c2</@td>
<@td>table_data_with_no_line_breaks_r2c3</@td>
</@tr>
</@table>
每个指令的实现大致如下:
class Table implements TemplateDirectiveModel {
public void exec(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) {
env.getOut().write("<custom_table>");
body.render(env.getOut());
env.getOut().write("</custom_table");
}
}
其他指令也有类似的实现。我希望实际输出如下(每行应该在一行中,没有前导或尾随空格):
<custom_table>
<row><column>data</column><column>data</column></row>
<row><column>data</column><column>data</column></row>
</custom_table>
我该如何实现这一目标?我可以使用<#t>
在每行末尾添加指令来修剪空白,但这看起来很笨拙,模板作者有时可能会忘记将其放入。有什么指点吗?
最佳答案
您应该浏览 Freemarker 的 White-space handling
一个选项是剥离空白
If this feature is enabled for a template, then it automatically ignores (i.e. does not print to the output) two kind of typical superfluous white-space:
例如ftl内
Tells information about the template for FreeMarker and for other tools, also helps programs to automatically detect if a text file is an FTL file. This directive, if present, must be the very first thing in the template. Any white-space before this directive will be ignored.
设置strip_whitespace参数值为true
strip_whitespace: This enables/disables white-space stripping.
其他选项是使用压缩指令
As opposed to white-space stripping, this works directly on the generated output, not on the template. That is, it will investigate the printed output on the fly, and does not investigate the FTL program that creates the output. It aggressively removes indentations, empty lines and repeated spaces/tabs
<#compress>
关于java - 抑制自定义 FreeMarker 指令的所有空格和新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729910/