parsing - macros not rendering in NVelocity -
i have simple set of velocity templates. when trying merge using nvelocity, macros other templates not executing. template contents follows:
v1.vm
#parse("v2.vm") #foreach( $customer in $customers) hello $customer.name! #set($a =$customer.getage()) #age($a) #end
v2.vm
#macro ( age $a ) #if($a<18) minor #else major #end #end
on merge, output is:
hello user1! #age(33) hello user2! #age(13)
the macro doesn't work because nvelocity (and ancestor velocity) determine if #age
directive or macro @ parse time, while #age
macro gets discovered @ runtime jumps other template, , passed through text.
to around need make macro available parser before parses v1.vm
's #foreach
. can putting macro inline in file, assume intend reuse in other templates why you've got separate now.
the other option put macro in macro library, either 1 nvelocity automatically load (vm_global_library.vm
) or custom one. if create template named vm_global_library.vm
@ root of templates directory nvelocity automatically load first before parsing anything, otherwise create own macro template file , register velocityengine
velocimacro.library
property. see velocity documentation more detailed explanation of properties.
i've included working example of using custom macro library:
class customer { public string name { get; set; } public int age { get; set; } public int getage() { return age; } } class program { static void main(string[] args) { velocityengine velocityengine = new velocityengine(); extendedproperties extendedproperties = new extendedproperties(); extendedproperties.setproperty(runtimeconstants.file_resource_loader_path, "templates"); extendedproperties.setproperty(runtimeconstants.vm_library, "mymacros.vm"); velocityengine.init(extendedproperties); velocitycontext context = new velocitycontext(); context.put("customers", new customer[] { new customer { name = "jack", age = 33 }, new customer { name = "jill", age = 13 } }); using (stringwriter sw = new stringwriter()) { bool result = velocityengine.mergetemplate("v1.vm", context, sw); console.writeline(sw.tostring()); } } }
Comments
Post a Comment