Calling Macro function in Velocity template

与世无争的帅哥 提交于 2021-02-06 15:10:41

问题


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.


回答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 )" )



回答2:


To get rid of spaces and blank lines use multi-line comments (#* comment *#):

#macro( myMacro $param )#*
  *#the_return_value#*
*##end



回答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/>



回答4:


A macro parameter can be a list of objects. The called macro can extract each object from the list, manipulate it, and then the caller will see the changes.

#macro(call $something)
  #set($swallowOutput = $something)
#end

#macro(doSomething $out)
  #set($list=$out.get(0))
  #call($list.add("hallo-1")
  #call($list.add("hallo-2")
#end

#macro(doMoreComplexStuff)
  #set($myList=[])
  #doSomething([$myList])
  MyList now has $myList.size()) elements: $myList
#end



回答5:


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 )" )



回答6:


Or just write everything onto the same line:

#macro( myMacro $param ) the_return_value #end


来源:https://stackoverflow.com/questions/6914312/calling-macro-function-in-velocity-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!