![](/img/trans.png)
[英]How to programmatically create a Drupal Commerce product with price
[英]How to display product.variation_price without currency in Drupal Commerce?
我需要在模板commerce-product.html.twig
中顯示產品價格
變量{{ product.variation_price }}
呈現為貨幣和數字,例如USD700
而且我不明白如何只顯示沒有貨幣的數字?
有兩種方法可以實現這一點:
Commerce Currency Settings module
。hook_commerce_currency_info_alter()
。由於任務非常簡單,並且很可能在初始設置后永遠不需要更新,因此無需安裝另一個模塊。 這意味着從長遠來看需要考慮和更新的組件更少,管理頁面也更少。
通過在您的自定義模塊中實現它,您還可以完全自由地更改顯示值的格式。 您可以用USD
替換美元符號,將其移動到值before / after
,或者添加custom labels
。
這是您需要使用的代碼:
/**
* Implements hook_commerce_currency_info_alter().
*/
function YOUR_MODULE_commerce_currency_info_alter(&$currencies) {
// Get the abbreviation of the default currency. This will return "USD" for
// US Dollars, "EUR" for Euros, etc.
// If your site is using multiple currencies, you can skip this and just use
// the abbreviation of the currency you want to change the format for.
$default_currency = commerce_default_currency();
$currencies[$default_currency]['format_callback'] = 'YOUR_MODULE_commerce_currency_format';
}
/**
* Commerce currency format callback.
*/
function YOUR_MODULE_commerce_currency_format($amount, $currency, $currency_code, $object = NULL, $convert = TRUE) {
// Format the price as a number.
$price = number_format($amount, 2, $currency['decimal_separator'], $currency['thousands_separator']);
// Establish the replacement values to format this price for its currency.
$replacements = array(
'@code_before' => $currency['code_placement'] == 'before' ? '' : '', //Here you can set empty or put $currency['code']
'@symbol_before' => $currency['symbol_placement'] == 'before' ? '' : '', // set empty or $currency['symbol']
'@price' => $price,
'@symbol_after' => $currency['symbol_placement'] == 'after' ? '' : '', // set empty or $currency['symbol']
'@code_after' => $currency['code_placement'] == 'after' ? '' : '', //set empty or $currency['code']
'@negative' => $amount < 0 ? '-' : '',
'@symbol_spacer' => $currency['symbol_spacer'],
'@code_spacer' => $currency['code_spacer'],
);
return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}
注意:如果將
hook_commerce_currency_info_alter()
實現放在YOUR_MODULE.commerce.inc
文件中,回調仍需要放在.module
文件中,因為.commerce.inc
文件不會自動加載到所有地方。
就是這樣 - 所有價格都將在沒有貨幣代碼的情況下顯示。
好吧,我剛剛自己找到了答案。
如果產品只有一種變體,我們可以在 Twig 中獲取其價格,如:
{% set price_number = product.variation_price['#items'].0.number %}
現在,根據顯示價格,我們可以不帶小數部分打印它,例如:
{{ price_number|number_format(0) }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.