Velocity (VM) template request parameters: Getting GET variables

21,065

Solution 1

Another option would be to use $httpUtil, a Liferay utility class that's injected in Velocity templates. This way you could do the following:

#set($url = $request.attributes.CURRENT_URL)
#set($singleValue = $httpUtil.getParameter($url, "foo", false))
#set($multipleValues = $httpUtil.getParameterMap($httpUtil.getQueryString($url)).foo)

Solution 2

$request.getParameter("parameterName")

Solution 3

I couldn't find the supposed solution in the terrible documentation, so i came up with this:

#set($curl = $request.get("attributes").get("CURRENT_URL"))
#set($foo = $curl.split("foo="))
<hr>
#if($foo.size() > 1)
  #set($foo1 = $foo.get(1).split("&").get(0))
  foo1: $foo1
#end
<hr>
#if($foo.size() > 2)
  #set($foo2 = $foo.get(2).split("&").get(0))
  foo2: $foo2
#end
<hr>
Share:
21,065
Cees Timmerman
Author by

Cees Timmerman

"Justice without force is powerless; force without justice is tyrannical." ~ Blaise Pascal (1623 – 1662) "Give a small boy a hammer, and he will find that everything he encounters needs pounding." ~ Abraham Kaplan (1918 – 1993), The Conduct of Inquiry: Methodology for Behavioral Science, 1964, page 28. "All that is complex is not useful; all that is useful is simple." ~ Mikhail Kalashnikov (1919 – 2013) "The cost of a mistake is the time required to correct it. With powerful languages and good programming environments, this cost can be greatly reduced. Programming style can then depend less on planning and more on exploration." ~ Paul Graham (1964 – ), ANSI Common Lisp, 1995.

Updated on July 09, 2022

Comments

  • Cees Timmerman
    Cees Timmerman almost 2 years

    How do i access GET variables as passed in the URI in a VM template?

    This works only when loading the widget URL:

    $request.get("parameters").get("fav").get(0)
    

    I'm looking for a neat solution that works with friendly URLs.

    Here's my testing template:

    <br><br><br>
    #set($url = $request.attributes.CURRENT_URL)
    
    <h2>url: $url</h2>
    
    #set($favs = $url.split("fav="))
    favs: $favs<br>
    favs.size(): $favs.size() <br>
    #if($favs.size() > 1)
      #set($fav1 = $favs.get(1).split("&").get(0))
      fav1: $fav1<br>
    #else
      No fav!
    #end
    #if($favs.size() > 2)
      #set($fav2 = $favs.get(2).split("&").get(0))
      fav2: $fav2<br>
    #end
    
    #set($favs2 = $httpUtil.getParameterMap($url, "fav"))
    favs2: $favs2
    
    <hr>
    <h3>Fav?</h3>
    <form method="get">
      <input type="checkbox" name="fav" value="dave"/> Dave<br>
      <input type="checkbox" name="fav" value="nate"/> Nate<br>
      <input type="checkbox" name="fav" value="taylor"/> Taylor<br>
      <input type="submit" value="Send"/>
    </form>
    <hr>
    <div style="font-size: 9px;">request: $request</div>