Wednesday, April 21, 2021

Drupal 8 - call function from twig template

Drupal 8 - call function from twig template:

Create a service yml file 'module_name.services.yml'

services:
  unique_function_name:
    classDrupal\module_name\Service\ClassName
    tags:
      - { nametwig.extension }

Create a service class 'src/Service/ClassName'

<?php 
namespace Drupal\module_name\Service;

use Drupal\taxonomy\Entity\Term;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_product\Entity\ProductAttributeValue;

/**
 * Class IBSearch.
 *
 * @package Drupal\ibsearch
 */
class ClassName extends AbstractExtension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'unique_function_name';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return [
      new TwigFunction('ib_get_term_name', [$this'getTermName']),
      new TwigFunction('ib_get_attr_name', [$this'getAttrName']),
      new TwigFunction('ib_get_format', [$this'getFormat']),
      new TwigFunction('ib_format_amount', [$this'formatAmount']),
    ];
  }

  /**
   * The php function to load a given block
   */
  public function getTermName($tid) {
    // Normalize if $tid is a Markup
    $tid = "".$tid;
    $term = Term::load($tid);
    if ($term) {
      return $term->getName();
    }
    return '';
  }

  public function getAttrName($attrId) {
    $attrObject = ProductAttributeValue::load($attrId);
    return is_null($attrObject) ? '' : $attrObject->get('name')->value;
  }

  public function getFormat(Product $commerce_product) {
    $variations = $commerce_product->getVariations();
    $format = array();
    foreach ($variations as $variation) {
      $value = $variation->getAttributeValue('attribute_format');
        $retval[] = $value->getName();
    }
    return implode(' | '$retval);
  }

  public function formatAmount(string $amount) {
    $price = number_format((float)$amount2"."",");
    return str_replace(".00"""$price);
  }
}

Now call your function from twig file:

{{ ib_format_amount(item.content["#markup"]) }}

Thanks for reading...

No comments:

Post a Comment

Change priority of dual boot OS

Change priority of dual boot OS  (Windows and Linux): Go to your Linux OS, install Grub customizer. Then change priority by up and down arro...