You are here

public static function PriceTwigExtension::formatPrice in Price 8

Same name and namespace in other branches
  1. 3.x src/TwigExtension/PriceTwigExtension.php \Drupal\price\TwigExtension\PriceTwigExtension::formatPrice()
  2. 2.0.x src/TwigExtension/PriceTwigExtension.php \Drupal\price\TwigExtension\PriceTwigExtension::formatPrice()
  3. 2.x src/TwigExtension/PriceTwigExtension.php \Drupal\price\TwigExtension\PriceTwigExtension::formatPrice()
  4. 3.0.x src/TwigExtension/PriceTwigExtension.php \Drupal\price\TwigExtension\PriceTwigExtension::formatPrice()

Formats a price object/array.

Examples: {{ order.getTotalPrice|price_format }} {{ order.getTotalPrice|price_format|default('N/A') }}

Parameters

mixed $price: Either a Price object, or an array with number and currency_code keys.

Return value

mixed A formatted price, suitable for rendering in a twig template.

Throws

\InvalidArgumentException

File

src/TwigExtension/PriceTwigExtension.php, line 43

Class

PriceTwigExtension
Provides Price-specific Twig extensions.

Namespace

Drupal\price\TwigExtension

Code

public static function formatPrice($price) {
  if (empty($price)) {
    return '';
  }
  if ($price instanceof Price) {
    $price = $price
      ->toArray();
  }
  if (is_array($price) && isset($price['currency_code']) && isset($price['number'])) {
    $currency_formatter = \Drupal::service('price.currency_formatter');
    return $currency_formatter
      ->format($price['number'], $price['currency_code']);
  }
  else {
    throw new \InvalidArgumentException('The "price_format" filter must be given a price object or an array with "number" and "currency_code" keys.');
  }
}