Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object within a velocity template

Tags:

velocity

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.

like image 848
EvilAmarant7x Avatar asked Sep 07 '12 15:09

EvilAmarant7x


1 Answers

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.

like image 85
p.mesotten Avatar answered Oct 07 '22 02:10

p.mesotten