简体   繁体   中英

grails gsp variables: how to pass as parameter of controller method in gsp

I have the following variable in my gsp page

<g:set var="valueDiscounted" value="${new ReceiptController().calculateDiscount(receiptInstance.totalAmount,
                                                                                receiptInstance.discount)}" />

the valueDiscounted variable gets its value from a controller method named calculateDiscount . Now, I need to use this variable as a parameter of another controller method, that I need to call in the same gsp. That is:

<td>Amount to pay: </td><td>€ ${new ReceiptController().calculateVat(${valueDiscounted},
        receiptInstance.vatPercentage)}</td>

This way is not correct, so how can I pass valueDiscounted to calculateVat method?

It's generally regarded as a bad design to try and call controller methods from views. Instead you should put the logic into a taglib , which both controllers and views can call.

Or in this case, put the calculations into the controller action, storing the calculated values in the model, then the view just needs to render values from the model rather than calculating anything itself.

Have you tried use valueDiscounted without ${}:

<td>Amount to pay: </td><td>€ ${new ReceiptController().calculateVat(valueDiscounted,
        receiptInstance.vatPercentage)}</td>

or, try to g:set amountToPay, and then use it in , similar to this:

<g:set var="amountToPay" value="${new ReceiptController().calculateVat(valueDiscounted,
        receiptInstance.vatPercentage)}" />
<td>Amount to pay: </td><td>€ ${amountToPay}</td>

I havent tried it, just quesing.

Sometimes I pass a service instance to model.

//MyService
def calculateDiscount(def totalAmount, def discount){
    // logic here
}
def calculateVat(def valueDiscounted, def vatPercentage){
    // logic here
} 

//MyController
def myService
def index(){
    ['instance':receiptInstance, 'service': myService]
}

//GSP
<g:set var="valueDiscounted" value="${service.calculateDiscount( instance.totalAmount, instance.discount)}" />
    ...
€ ${service.calculateVat(valueDiscounted, instance.vatPercentage)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM