velocity template loop through array to create string

╄→гoц情女王★ 提交于 2020-08-10 19:30:05

问题


I'm trying to use the velocity templating language in an AWS appsync resolver to create a string by looping through an array of characters.

Given the array listOfWords = ["好" "克力"] how would I achieve the string output of queryString = "+\"好\" +\"克力\""

So far I have managed something like this:

24: #set($listOfWords = ["好" "克力"])
25: #set($queryString = "")
26: #foreach($word in $listOfWords)
27:   #if( $velocityCount == 1 )
28:     #set($queryString = "+\"$word\"")
29:   #else
30:     #set($queryString = $queryString +"+\"$word\"")
31:   #end
32: #end

This returns the error: Encountered \"$word\" at velocity[line 28, column 37]\nWas expecting one of:\n <RPAREN> ...\n <WHITESPACE> ...\n \"-\" ...\n \"+\" ...\n \"*\" ...\n \"/\" ...\n \"%\" ...\n <LOGICAL_AND> ...\n <LOGICAL_OR> ...\n <LOGICAL_LT> ...\n <LOGICAL_LE> ...\n <LOGICAL_GT> ...\n <LOGICAL_GE> ...\n <LOGICAL_EQUALS> ...\n <LOGICAL_NOT_EQUALS> ...\n

I have also tried

#foreach( $word in $listOfWords )
        #if( $velocityCount == 1 )
            #set($queryString = "+" + "\\" + "\"" + $word + "\\" + "\"") line 27
        #else
            #set($queryString = $queryString + "+" + "\\" + "\"" + $word + "\\" + "\"")
        #end
    #end
    )

But seem to be causing a lexical error:

"Lexical error, Encountered: \"\\\"\" (34), after : \"\\\\\\\\\" at *unset*[line 27, column 64]"


回答1:


You can do that:

#set($listOfWords = ["好" "克力"])
#set($q = '"')
#set($queryString = "")
#foreach($word in $listOfWords)
  #if( $velocityCount == 1 )
    #set($queryString = "$q$word$q")
  #else
    #set($queryString = "$queryString+$q$word$q")
  #end
#end



回答2:


Rather than building up a VTL variable, you could just build up the string as the output directly. Kind of like this example from the VTL docs;

<ul>
  #foreach( $product in $allProducts )
    <li>$product</li>
  #end
</ul> 


来源:https://stackoverflow.com/questions/62713626/velocity-template-loop-through-array-to-create-string

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