Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert a string to number in freemarker template

Tags:

I want to convert a string to number in freemarker. I want to put some conditional check based on the value of the number. ?number doesn't seems to work.

Any suggestions?

like image 645
Mady Avatar asked Jun 07 '12 08:06

Mady


People also ask

What does c mean in FreeMarker?

c (when used with numerical value) This built-in converts a number to string for a "computer language" as opposed to for human audience. That is, it formats with the rules that programming languages used to use, which is independent of all the locale and number format settings of FreeMarker.

How do you generate random numbers in FreeMarker?

Freemarker does not provide a random number generator at the moment. You can implement a naive random number generator using the time ( . now ) as a seed, but it should never be a critical part of your program.

How do you escape characters in FreeMarker?

Both quotation mark (") and apostrophe-quoate (') are escaped. Starting from FreeMarker 2.3. 1, it also escapes > as \> (to avoid </script>). Furthermore, all characters under UCS code point 0x20, that has no dedicated escape sequence in JavaScript language, will be replaced with hexadecimal escape (\xXX).

How do you use the ternary operator in FreeMarker?

When applied to a boolean, the string built-in will act as a ternary operator. It's no very readable as this is not the intended usage of it. It's for formatting boolean values, like Registered: ${registered? string('yes', 'no')} .


2 Answers

Sorry, ?number does work fine. I was not able to compare the converted number with another number.

This didn't work for me:

<#assign num = numString?number>  <#if num > 100> </#if> 

When I enclosed (num > 100) inside the brackets it worked:

<#if (num > 100)> </#if> 

Since the comparison was not working, I was assuming that conversion was not happening. My bad.

like image 173
Mady Avatar answered Sep 20 '22 10:09

Mady


In your code, you use the closed bracket, so freemarker is evaluating

<#if num > 

you should instead use

<#if num gt 100> 

This is discussed at the end of this documentation on if statements https://freemarker.apache.org/docs/ref_directive_if.html

The reason this is working for some and not others is because of the parentheses, which is also explained at the bottom of the documentation

like image 37
Tay Moore Avatar answered Sep 18 '22 10:09

Tay Moore