API / Apache Velocity Interview questions
How do you handle internationalization (i18n) in Velocity templates?
Velocity itself has no built-in i18n mechanism, VTL has no concept of locale, so translated text is handled by pairing standard Java ResourceBundles with VelocityTools' ResourceTool, which is exposed into the context (commonly under the key $text).
## messages_en.properties: welcome.greeting=Welcome, {0}! ## messages_fr.properties: welcome.greeting=Bienvenue, {0}! $text.get("welcome.greeting", $user.firstName)
The Locale itself typically comes from the incoming HTTP request (an Accept-Language header) or a user preference stored in session, and gets set on the tool per request rather than being fixed globally, so the same template renders correctly for different users without any template-side branching on language.
This keeps translated strings entirely out of the .vm files, which matters since hardcoding text in templates would mean a code change (and redeploy) for every new translation instead of just adding a new properties file.
More Related questions...