Handy regex for adding inline translations to Magento template files

When developing Magento themes, you will quite often have flat HTML that you are breaking apart and putting into Magento’s template files. One thing that I have OCD-like tendencies with is the need to make sure that all text is in an inline translate. By that I mean using:

<?php echo $this->__('Basket') ?>

Obviously, this is good practice to have when building any Magento store! However, it can sometimes mean a lot of repetitive typing, so I decided to use a regular expression instead to replace text automatically. I’ve tended to use textmate during development and so have used the following for “Find and Replace”, but they can easily be converted to be used in your text editor or IDE of choice.

Find this:

([^-])>([^<\s][^<]*)<

Replace with:

$1><?php echo $this->__("$2") ?><

This snippet will work even if the file already includes some inline translates. I've tested it a bit, but if anyone finds some edge cases where it doesn't work, then let me know.

For "$2" I'd normally use single quotes, but the current regex won't look for and escape the string if it already contains a quote, e.g. an apostrophe. So I've left it as double quotes as these are less likely to appear in strings.

Note this regex won't replace attributes e.g. alt and title tags. Just the content within elements.

This entry was posted in Magento Development. Bookmark the permalink.

2 Responses to Handy regex for adding inline translations to Magento template files

  1. Denis says:

    Thanks TomGood point re: Mage_* being ordvrieden.In a quick test I deleted /app/locale/en_GB/ and created a translate.csv in a new locale/en_GB directory below my store theme. ‘Add To Cart”,”Add To Test” translation worked.Leaving that file in place I then re-added /app/locale/en_GB/* and those appear to take precedence over the translate.csv file.Using a theme-based translate.csv suites my needs, so I’ll take that approach.John

  2. MagePsycho says:

    If you are using #Netbeans then you are lucky enough to use Macros for converting label/text for inline translation.
    You can find more info about Macros in order to use with Magento templating here: http://www.blog.magepsycho.com/using-netbeans-macros-to-speed-up-magento-templating/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>