Velocity (VM) template request parameters: Getting GET variables

Cees Timmerman picture Cees Timmerman · Dec 7, 2011 · Viewed 20.8k times · Source

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>

Answer

p.mesotten picture p.mesotten · Dec 8, 2011

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)