Keep the Currency Out of Your Templates

No Gravatar

I was recently tasked with creating e-commerce sites for countries where dollar signs don’t apply. Symfony’s I18N support was great for translating strings but proved to be inadequate for formatting currency. Having only used our e-commerce software to display currency in either American or Canadian dollars I had to first remove all hard coded dollar signs from our templates and invent a generic way to display currency for different regions.

Symfony’s format_currency() almost gets the job done, so I created a helper which augments its output. There’s nothing fancy here. You can add a currency indicator on either the left or the right of the currency, and if neither a left or right currency indicator are configured, we default to showing a dollar sign.

<?php
 
function cws_format_currency($price)
{
	sfContext::getInstance()->getConfiguration()->loadHelpers('Number');
 
	$left = sfConfig::get('app_currency_indicator_left', '');
	$right = sfConfig::get('app_currency_indicator_right', '');
 
	if ($left === '' && $right === '')
		$left = '$';
 
	return
		$left.
		format_currency($price).
		$right;
}

Leave a Reply