Puya Sarmidani
Puya Sarmidani

Reputation: 1289

Calling a function inside a twig for loop

How can i call a function inside a twig for loop. I have a array output of the database and i call it inside twig like this:

<tbody>
{% for O in Orders %}
<tr>
<td>{{ O.DomainName~'.'~O.Extension }}</td>
<td>{{ O.Package }}</td>
<td>{{ O.StoreDate }}</td>
<td>{{ O.ExecuteDate }}</td>
<td>{{ O.Email }}</td>
<td>{{ O.UserIP }}</td>
<td></td>
</tr>
{% endfor %}
</tbody>

UserIP wil return the IP Address. What i want to accomplish is to call the function below for every user and add that to the table.

    public function ip_country($userIP)
{
    $ip = $userIP;
    $details = json_decode(file_get_contents("http://freegeoip.net/json/{$ip}"));

    return $details->country_code; // -> "US"
}

Now i know that i can not call a function directly from twig. Do i need to add that as a twig extension with twig_simplefunction?

Upvotes: 0

Views: 1386

Answers (1)

Omar Alves
Omar Alves

Reputation: 763

Create a twig extension and wrap your code inside it. Your code will get more clean and won't pollute the views and controllers.

First create a filter

namespace AppBundle\Twig;
class MyIpExtension extends \Twig_Extension {
  public function getFilters()
  {
    return array(
        new \Twig_SimpleFilter('ipcountry', array($this, 'country')),
    );
  }

  public function ip_country($userIP) {
    $ip = $userIP;
    $details = json_decode(file_get_contents("http://freegeoip.net/json/{$ip}"));

    return $details->country_code; // -> "US"
 }


  public function getName()
  {
     return 'app_extension';
  }
}

And then register as a symfony container service

# app/config/services.yml
services:
   app.twig_extension:
      class: AppBundle\Twig\MyIpExtension
      public: false
      tags:
        - { name: twig.extension }

And then use the extension in your twig views

{{ O.UserIP | ipcountry }}

Pay close attention on class names and namespaces. Make the necessary adaptation to your environment.

Upvotes: 2

Related Questions