Shared variables

共享变量 是为所有模板定义的变量。您可以使用setSharedVariable方法将共享变量添加到配置中:

Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
...
cfg.setSharedVariable("warp", new WarpDirective());
cfg.setSharedVariable("company", "Foo Inc.");

在所有使用此配置的模板中,名称为wrap的用户定义指令和名称为company的字符串将在数据模型根目录中可见,因此您不必一次又一次地将它们添加到根哈希中。传递给Template.process的根对象中的变量将隐藏具有相同名称的共享变量。

Warning!

如果配置被多个线程使用,切勿对共享变量使用不是thread-safeTemplateModel实现!这是基于 Servlet 的应用程序的典型情况。

由于具有向后兼容性的传统,因此共享变量集最初(即对于新的Configuration实例)不为空。它包含以下用户定义的指令(就您使用@而不是#而言,它们是“用户定义的”):

nameclass
capture_outputfreemarker.template.utility.CaptureOutput
compressfreemarker.template.utility.StandardCompress
html_escapefreemarker.template.utility.HtmlEscape
normalize_newlinesfreemarker.template.utility.NormalizeNewlines
xml_escapefreemarker.template.utility.XmlEscape