Steve McLeod
Steve McLeod

Reputation: 52448

Using a constant in multiple freemarker templates

I'm using Freemarker templates to generate HTML. I have this line repeated in several templates:

<link href="/css/main.css?v=${css_version}" rel="stylesheet">

I want to be able to specify a value for css_version just once, and use it in all my templates. How can I do this?

Upvotes: 0

Views: 502

Answers (1)

ddekany
ddekany

Reputation: 31112

Possibly like this:

Configuration cfg ...
...
cfg.setSharedVariable("css_version", "1.2.3");

Note that you should do this where you set up your singleton Configuration instance, and it's not thread safe to call setSharedVariable later. So if css_version has to change without recreating the Configuration, then instead of a String simply use a custom TemplateScalarModel implementation that reads the version number from some thread-safe source. (That is, the value of a shared value can change over time, as far as the template sees it, even though the actual shared variable object isn't replaced.)

Upvotes: 2

Related Questions