php - How to commission in twig?

793

I have function to payments

public function calculateClientCost(Transaction $transaction)
{
    if ($transaction->getPaymentType() == Order::PAYMENT_TYPE_ALTERNATIVE) {
        return $this->container->getParameter('commission_alternative_price');
    }

    if ($transaction->getPaymentType() == Order::PAYMENT_TYPE_PRICE) {
        return $transaction->getPrice();
    }
}



public function calculateCommission(Transaction $transaction)
{
    if ($transaction->getPaymentType() == Order::PAYMENT_TYPE_ALTERNATIVE) {
        return $this->container->getParameter('commission_alternative_price');
    }

    if ($transaction->getPaymentType() == Order::PAYMENT_TYPE_PRICE) {
        return round($this->container->getParameter('commission_publisher') * $transaction->getPrice() / 100, 2);
    }
}

and there is a problem i want to use the function in my twig. My twig looks like

<span class="rab_mobile">{{ 'table.head.net_price'|trans }}:</span>
{% if t.isNormalPrice() %}
    {{ t.price|localizedcurrency(currency) }}
{% else %}
    <em>{{ t.alternativePayment|slice(0,15) }}</em>
{% endif %}

I want to add commission in twig. Can anyone suggest me how I can do this? Thanks in Advance.

916

Answer

Solution:

If you want to use a php function in Twig, you might need to create a new extension.

class calculateThingsForPaymentsExtension extends \Twig_Extension
{
    public function calculateCommission(Transaction $transaction)
    {
        if ($transaction->getPaymentType() == Order::PAYMENT_TYPE_ALTERNATIVE)
        {
            //your logic
        }
    }

    public function getFunctions()
    {
        return (array(new \Twig_Function('calculateCommission',
                                         array($this, 'calculateCommission'))));
    }
}

And then, in Twig

{% set commission = calculateCommission(transaction) %}

I used this in Symfony 4 and my class was automatically registered as service and could be used as is.

Assuming you're using Twig with Symfony, you can read the documentation for more informations.

People are also looking for solutions to the problem: php - Angular 5 Ionic 3 Laravel project structure

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.