On this page
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-safe的TemplateModel
实现!这是基于 Servlet 的应用程序的典型情况。
由于具有向后兼容性的传统,因此共享变量集最初(即对于新的Configuration
实例)不为空。它包含以下用户定义的指令(就您使用@
而不是#
而言,它们是“用户定义的”):
name | class |
---|---|
capture_output |
freemarker.template.utility.CaptureOutput |
compress |
freemarker.template.utility.StandardCompress |
html_escape |
freemarker.template.utility.HtmlEscape |
normalize_newlines |
freemarker.template.utility.NormalizeNewlines |
xml_escape |
freemarker.template.utility.XmlEscape |