javatemplatesvelocityvelocity-template-language

Velocity Template - Show and Hide


I have the following velocity template.


    <tr>
    <td>Address 1*</td>
    <td>:<b> $currentAddressAddress1 </b> </td>
    </tr>
    #if ($currentAddressAddress2)
    <tr>
    <td>Address 2</td>
    <td>:<b> $!currentAddressAddress2 </b> </td>
    </tr>
    #end

The second row should be displayed only if currentAddressAddress2 has value in it. Otherwise it should not display. But I am getting the following as output

Address 1* : RJ street

Address 2 :

But I want ,

Address 1* : RJ street

only


Solution

  • Nulls in velocity are very fiddly (this will provide some insight on how to check for nulls: https://cwiki.apache.org/confluence/display/velocity/CheckingForNull). I'm assuming $currentAddressAddress2 is a String? In which case if it is not null then your check will return true. There are a few options available, but one is:

    #if($!currentAddressAddress2 != "")
    

    This is obviously not a great solution, it doesn't cater for blank strings for example, only empty. One other option is you could add Apache StringUtils into your request from your controller and use isNotEmpty to check it has a "real" value.