Last Updated: February 25, 2016
· xander

Importing 2 or more macros as a single namespace // Freemarker

While working with macros in freemarker you might find yourselve in a need to use different macros which have the same name. In other cases you might need to extend one set of macros with another.

Importing instead of including

Imagine that you have a set of macros saved in a file called macrosA containing macros a, b and c (sorry for being so little creative ;] ). You can import it:

<#import "path/to/macros/macrosA" as macros>

The macros will be loaded as macros so You can use those like

<@macros.a />
<@macros.b />
<@macros.c />

That's how you do namespacing. If you have i.e. macro called 'a' in another file called macrosB then You can load that file with different name and you will be able to use both macros in the same template.

<#import "path/to/macros/macrosA" as macrosA >
<#import "path/to/macros/macrosB" as macrosB >

<@macrosA.a />
<@macrosB.a />

Extending one macro with another

Now imagine that you've got a set of macros in a file called macrosA and you want to extend that set with macros from macrosB.

When you do

<#import "path/to/macros/macrosA" as smth>

then smth becomes a hash containg all macros from inside macrosA. That means you can operate on it as you would operate on hashes in freemarker (exactly the same way as you would deal with e.g. JSON in freemarker).

You can easily add one hash to another:

<#import "path/to/macros/macrosA" as macrosA >
<#import "path/to/macros/macrosB" as macrosB >

<#assign allmacros = macrosA + macrosB>

Now allmacros will contain all macros defined in both files. If there is a macro of the same name in macrosA and macrosB then macro from macrosB will override macro from macrosA.

That's it

Simple and useful - isn't it?
Credits go to @mateuszgachowski for teaching me that. Thanks dude ;]