Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Localized image Helper

Returns localized image <img> tag bassed on the the user culture and the image file location in the filesystem.

Based on the technique recomended in the symfony advent calendar day twenty-three

Directory tructure:

Inside images directory, create one directory for each culture in use plus one (named 'no-loc' by default) for non-localized images or images that doesn't change for different cultures.

Example:

web/images/en_US
web/images/es_MX
web/images/fr_FR
................
web/images/non-loc

<?php
/**
 * Returns localized image <img> tag bassed on the the user culture
 * and the image file location in the filesystem
 * 
 * If the image file is found under the directory corresponding
 * the user culture, it returns its img tag,
 * else returns img tag under 'non-loc'directory.
 * 
 *  Structure example:
 * 
 *   web/images/en_US
 *   web/images/es_MX
 *   web/images/fr_FR
 *   ................
 *   web/images/non-loc
 * 
 * $source   -  relative path within culture directory
 * $options  -  is a normal options array passed to image_tag function
 * 
 */
function local_image_tag($source, $options = array())
{
  $images_path       = sfConfig::get('sf_root_dir') . '/web/images';
  $non_localized_dir = 'non-loc';
  $culture           = sfContext::getInstance()->getUser()->getCulture();
  $default_ext       = 'png';
 
  if (strpos(basename($source), '.') === false)
  {
    $source .= '.'.$default_ext;
  }
 
  if (!$culture || !(is_file($images_path.'/'.$culture.'/'.$source)))
  {
    return image_tag($non_localized_dir.'/'.$source, $options);
  }
 
  return image_tag($culture.'/'.$source, $options);
}
?>

Call example:

<?php
echo local_image_tag('some/image', 'alt=image');
/*
Will search in /web/images/<culture>/some/image.png,
and if file is not found, will return image tag in
/web/images/non-loc/some/image.png
*/
?>
by David Regla on 2006-05-25, tagged helper  i18n 

Comments on this snippet

gravatar icon
#1 Marc Llopart Riera on 2007-04-11 at 06:22

I've modified the snippet and I've added the next function for submit_image_tag:

function local_submit_image_tag($source, $options = array()) { $images_path = sfConfig::get('sf_root_dir') . '/web/images'; $non_localized_dir = 'non-loc'; $culture = sfContext::getInstance()->getUser()->getCulture(); $default_ext = 'png';

if (strpos(basename($source), '.') === false) { $source .= '.'.$default_ext; }

if (!$culture || !(is_file($images_path.'/'.$culture.'/'.$source))) { return submit_image_tag($non_localized_dir.'/'.$source, $options); }

return submit_image_tag($culture.'/'.$source, $options); }

You need to create an account or log in to post a comment or rate this snippet.