AnnetteC
AnnetteC

Reputation: 506

Velocity parse + global variables vs. macro

In my project I have a lot of html code blocks that I reuse at different places with slight variations. For example, I have a code block defining an info banner but the text and the color scheme is varying.

I see two ways to "include" it into my main template:

1.

#set( $infoBannerText = "This is an info banner..." )
#set( $infoBannerColor = "YELLOW" ) ## predefined map with color-related properties
#parse( "info-banner" )
  1. With having defined #macro( info_banner $infoBannerText $infoBannerColor ) before:
#info_banner( "This is an info banner..." "YELLOW" )

I see following advantages / disadvantages: The second one is more robust in terms of missing variable definitions or unintended overwriting of variables. Whereas the first one has a better performance and allows for a cleaner structure of the reusable parts which I can store in single files. Using macros feels like, that I will end up with a big macro file that lacks clarity.

Somehow, I prefer the first solution but would like to know what "Best Practise" is or what experience you have.

Upvotes: 0

Views: 430

Answers (1)

Claude Brisson
Claude Brisson

Reputation: 4130

You can mix the two ways:

#macro(info_banner, $infoBannerText, $infoBannerColor)
  #if(!$infoBannerText) Missing banner text! #end
  #if(!$infoBannerColor) Missing banner color! #end
  #parse('info-banner')
#end

#info_banner( "This is an info banner..." "YELLOW" )

I don't really see any performance problem in either way. A good practice can be to gather all the parsed blocs in some /inc/ subfolder so that they cannot be directly called as top level templates.

Upvotes: 1

Related Questions