user1414289
user1414289

Reputation: 11

Velocity Macros vs. Directives

What is considered to be best practice when extending the Velocity syntax. The two mechanisms available are Directives and Macros. Both look equally powerful. Directives require actual development of Java code, while Macros are just snippets of Velocity syntax.

The advantages of Directives being that because they are written in Java, you do not have to parse the extra Velocity syntax contained within the Macro. It makes the extension of Velocity more formal, and stops lots of uncontrolled additions.

On the plus side for Macros, I see this as being very flexible, and allowing a lot of re-use as common patterns are discovered during the development of the application.

So, your thoughts in this area would be most welcome.

Upvotes: 1

Views: 824

Answers (1)

Nathan Bubna
Nathan Bubna

Reputation: 6933

There's actually a third way too. But first...

Directives are for doing things to or with a section of a template, or things that require awareness of the template around them. For instance, you might create a directive that transforms the output of the section it encloses in some way. And they provide this functional, template-centric behavior in a global, always-on manner.

Macros were not designed to be functions. They are best used to repeat content or markup. They are made to keep you from ever putting any of whatever markup language (or whatnot) that you are outputting in Java code, or from repeating sections of VTL over and over.

The third way is called "tools". The VelocityTools project has many of these you can use or use as examples, not to mention support code for really easy tool management. Anyway, tools are primarily for accessing or manipulating your data. Don't create a directive or a macro that does number formatting. Use a tool. Tools provide a VTL-friendly interface to libraries and APIs that are otherwise difficult to use within templates. They can be access-controlled and scoped in ways that directives and macros never can.

All three are very useful, for different things. In short:

  • directives are best for manipulating the AST or the output of template sections
  • macros are best for not repeating yourself or letting markup sneak into java code
  • tools are best for accessing and manipulating the data in the template

Upvotes: 2

Related Questions