6

I want to compare two strings to decide whether the first string is 'smaller' than the second string.

<#if name1 <= name2>
....
</#if>

Error:

Can't use operator "<=" on string values.

Can this be done in FreeMarker? Is it possible to call the String.compareTo method in a template?

Joris Deevers
  • 61
  • 1
  • 3

2 Answers2

2

If you meant length, you can use the length built-in, for example:

<#if string?length gt 0>

If you mean to use a custom comparison and you are using Struts2, you can simply invoke an action method for it, let's assume you have a compare method:

public boolean compare(String str1, String str2) { ... }

then you can do this:

<#if action.compare(str1, str2) gt 0>
meskobalazs
  • 15,741
  • 2
  • 40
  • 63
  • How does the FreeMarker engine find the `compare` function? Where should it be implemented? Does it have to be `static`? – Joris Deevers Apr 27 '15 at 10:46
  • Well, here I assumed, that you are using Struts2. If this is not the case, it won't. If you do, it must be a public instance method of a Struts2 Action. – meskobalazs Apr 27 '15 at 10:46
  • No I am not using Struts2. – Joris Deevers Apr 27 '15 at 10:48
  • 1
    If you add any plain Java object with public methods to your data-model, or to the set of configuration-level shared variables, you can call its methods. You can also implement `TemplateMethodModelEx` and add that to your data-model or to your shared variables or pull it in in an `#import`-ed template like `<#assign strCmp = 'com.example.MyStringComparatorTemplateModel'?new()>`. – ddekany Apr 27 '15 at 18:16
0

In FreeMarker you can use == to compare Strings, but depending the meaning of <= for you, you can use BuiltIn for strings to compare the lenght, the content, or what you need.

UPDATE: you don't have built in method to compare lexicographically String in FreeMarker, so you have 2 options:

  1. Create your own method to compare the Strings with built-in functions, iterating over strings and comparing char by char.
  2. create a Java comparator as @meskobalazs suggest
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109