Question

I have the folowing code :

I want calculate the pattern of formatNumber with a number of decimal.

Call with jslt :

<td class="TD_Suivi"><fmt:formatNumber type="number" pattern="${getNumberFormatPatern(4)}" value="${toto.montant}" /> </td>

External javascript function :

function getNumberFormatPatern(nbDecimal) {
    "##,##0.00"
    var numberFormatPattern1="##,";
    var numberFormatPattern2 ="0.";
    for (i = 0; i < nbDecimal; i++) 
    { 
        numberFormatPattern1+="#";
        numberFormatPattern2+="0";
    }
    return numberFormatPattern1+numberFormatPattern2

Call of my javascript function :

<script language="JavaScript"
    src="<util:WebPath/>/js/commun/jsControle.js"></script>

And I have this following error :

The function getNumberFormatPatern must be used with a prefix when a default namespace is not specified
Was it helpful?

Solution

You cannot invoke a JavaScript function within an expression. Your container will generate content using expressions before the client begins processing the JavaScript on the page, so there is no way for the container to resolve the expression to invoke the function as is.

You have two choices:

  1. Refactor that logic to your backend

For example, if you are using servlets, this method would need to be accessible:

private String getNumberFormatPattern(int nbDecimal) {
    String numberFormatPattern1 = "##,";
    String numberFormatPattern2 = "0.";
    for (int i = 0; i < nbDecimal; i++) {
        numberFormatPattern1 += "#";
        numberFormatPattern2 += "0";
    }
    return numberFormatPattern1 + numberFormatPattern2;
}

You could then make this value available for an expression by associating it with the request:

request.setAttribute("numberFormatPattern", getNumberFormatPattern(4));

And reference it like so in an expression:

<fmt:formatNumber type="number" pattern="${ numberFormatPattern }" value="${ toto.montant }" />
  1. Refactor that logic into a custom function

Here is a straight-forward guide on the registration and usage of a custom function. You'd just need to replace the charAt function with your getNumberFormatPattern() function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top