Calling Macro function in Velocity template
Solution 1
Macros are not functions; they are for rendering output. However, if you don't mind losing the type and getting the result as text...
#set( $book_list_link = "#getBookListLink( $readingTrackerResult )" )
Solution 2
To get rid of spaces and blank lines use multi-line comments (#* comment *#
):
#macro( myMacro $param )#*
*#the_return_value#*
*##end
Solution 3
Instead of living with the string limitations for 'return values', preferably an externally defined result variable can be passed 'by reference', e.g.:
#macro(getBookListLink $inTrackerResult $outBookListLink)
#if ($outBookListLink)
#set ($outBookListLink = $inTrackerResult.getBookListLink())
#end
#end
#set ($myLink = "")
#getBookListLink($myTrackerResult $myLink)
myBookListLink = "$myLink"<br/>
Solution 4
Just another example to illustrate the principle :
Macro definition :
#macro ( getValue $flag )
#if ( $flag )
#set($value = "TRUE" )
#else
#set($value = "FALSE" )
#end
${value}## (ends with a comment to avoid "END-OF-LINE" in the resulting string)
#end
Call :
#set($myval = "#getValue( true )" )
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
I am trying to figure out how to return a value from a velocity macro call and assign it to a varaible
my macro function looks something like this. its once in common shared macros files
#macro(getBookListLink, $readingTrackerResult) $readingTrackerResult.getBookListLink() #end
I am need to assign the result of this macro to a variable in another velocity template file
I tried something like this
#set($book_list_link = #getBookListLink( $readingTrackerResult ))
but did not work. I tried with #,$ and with nothing in front of function getBookListLink. but nothing worked. Can not i return from a macro? something wrong with my macro?
But, As such if i call #getBookListLink( $readingTrackerResult ) separately in html file. it works and i can print the result to UI. But not able to assign to a variable.
-
Paramesh Korrakuti over 7 yearsIn case, if the function expects a string argument, then we need to use as follows:
#set( $book_list_link = "#getBookListLink('string_argument')" )