7

I've looked at this question already, but it's talking about liferay-velocity and seems to have access to this '$portal' object that I don't have access to.

Create object in velocity template

Specifically I'm trying to create a Locale object within the template to pass it into a $dateTool.format call to get the output in a specific language.

I can't create the locale object and pass it into the template beforehand because that code could call a variety of templates, each of which could be in different languages.

I've tried

#set($localeClass = $portal.getClass().forName("java.util.Locale"))
$localeClass.getName

but that just output '$localeClass.getName' (I wasn't sure if $portal was some magic pre-set variable or something).

I also tried

#set($localeClass = java.util.Locale.class)
$localeClass.getName

but that gave me a runtime exception when I tried to process the template.

I saw the ClassTool present in Velocity, but that doesn't support reflexive execution of code. I guess I could try something like $classTool.inspect("java.util.Locale").getType.getConstructor([$classTool.inspect("java.util.String"),$classTool.inspect("java.util.String")]).newInstance(["es","ES"]).

I'll try that out, but in the meantime I'll see if anyone else has a better idea.

EDIT

Since posting, I realized that velocity has a ConversionTool (which wasn't listed on their GenericTool overview page), that has a toLocale function I can call. So I can use

$dateTool.format('dd-MMM-yyyy', $date, $conversionTool.toLocale("es_ES"))

But I'm still curious if there was a way to accomplish this via reflection.

Community
  • 1
  • 1
EvilAmarant7x
  • 2,059
  • 4
  • 24
  • 33
  • I see this is old, but I'm on this for hours, I've added a new instance of ConversionTool to the Velocity context with the name conversionTool, but whenever I do a simple toLocale("en_GB") it complains about nullpointer in the format method at runtime. (on the line it uses the locale). Any things you had to set up? In a simple unit test it works fine. (calling toLocale) – Mathijs Segers Jan 13 '16 at 19:59

2 Answers2

1

You did it alright but you should use $localeClass.getName() or $localeClass.name instead of $localeClass.getName. See the Property Lookup Rules in the Velocity user guide.

This:

#set($localeClass = $portal.getClass().forName("java.util.Locale"))
$localeClass.getName()

correctly outputs the String "java.util.Locale" for me.

p.mesotten
  • 1,402
  • 1
  • 14
  • 26
0

As far as I understand you may also use

$localeUtil.fromLanguageId("es_ES")

for getting locale in a Velocity template.

As for me I've also tried to use reflection for getting locale recently but didn't succeed. So I'm curious if it's ever possible too.

Artem Shafranov
  • 2,655
  • 19
  • 19