Kai
Kai

Reputation: 2205

In Freemarker, how can I access custom attributes in a template file?

In a Freemarker template file, how can I access properties set using the freemarker.core.Configurable#setCustomAttribute(java.lang.String, java.lang.Object) method on a Template instance?

Or if this is not possible, how can I push some variables into the template before processing the payload, that I can access within the template file?

Cheers, Kai

Upvotes: 0

Views: 642

Answers (1)

ddekany
ddekany

Reputation: 31152

Custom attributes are for propagating the values in the opposite direction. You can't get custom attributes in templates, you can only set them there, in the #ftl header. For example, a template could specify the MIME type of its output there, and then what calls the template can set the content type of the HTTP response based on that.

If you have a data-model that's not specific to the template you call, and you need to pass some extra variables only to that template, that's a problem to solve on the data-model level. Like you could compose a new data-model with TemplateModelUtils.wrapAsHashUnion(ObjectWrapper, java.util.List<?>), and pass that to the template.

Alternatively, you can get the Template as usual, but then create its runtime environment with Template.createProcessingEnvironment, set the variables in the Environment, and then call Environment.process(). That's like calling some #assign-s from outside the template, before you actually start running the template.

Upvotes: 1

Related Questions