Shared variables - Apache FreeMarker Manual

Unsupported web browser - Use a modern browser to view this website!

- Home
- Manual
- Java API

- Contribute
- Report a Bug
- Download

Manual
Previous Next

# Shared variables

Shared variables are variables that are defined for all templates. You can add shared variables to the configuration with the `setSharedVariable` methods:

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

In all templates that use this configuration, an user-defined directive with name `wrap` and a string with name `company` will be visible in the data-model root, so you don't have to add them to the root hash again and again. A variable in the root object that you pass to the `Template.process` will hide the shared variable with the same name.

Warning!

Never use `TemplateModel` implementation that is not thread-safe for shared variables, if the configuration is used by multiple threads! This is the typical situation for Servlet based applications.

Due to backward compatibility heritage, the set of shared variables is initially (i.e., for a new `Configuration` instance) not empty. It contains the following user-defined directives (they are "user-defined" in the sense that you use `@` to call them instead of `#`):

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`

Previous Next