简体   繁体   English

grails gsp变量:如何在gsp中作为控制器方法的参数传递

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

I have the following variable in my gsp page 我的gsp页面中有以下变量

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

the valueDiscounted variable gets its value from a controller method named calculateDiscount . valueDiscounted变量从名为calculateDiscount的控制器方法获取其值。 Now, I need to use this variable as a parameter of another controller method, that I need to call in the same gsp. 现在,我需要将此变量用作另一个控制器方法的参数,需要在同一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? 这种方式是不正确的,那么如何将valueDiscounted传递给calculateVat方法?

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. 相反,您应该将逻辑放入taglib中 ,控制器和视图都可以调用该逻辑。

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 ${}: 您是否尝试使用不带$ {}的valueDiscounted:

<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 amountToPay,然后在中使用它,类似于:

<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)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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