Search code examples
javascriptphphtmlwebhardcode

Avoid hardcoding strings html


How should I go about avoiding hardcoding Strings in HTML code?

e.g:

<h1>Website name</h1>

So that they can be easily changed globally across the site from one location.


Solution

  • You could create separete html files with each lang, but I prefer to use another things as:

    PHP:

    $lang = array();
    
    $lang['PAGE_TITLE'] = 'My website page title';
    $lang['HEADER_TITLE'] = 'My website header title';
    $lang['SITE_NAME'] = 'My Website';
    $lang['SLOGAN'] = 'My slogan here';
    $lang['HEADING'] = 'Heading';
    

    More info for this custom method here: http://www.bitrepository.com/php-how-to-add-multi-language-support-to-a-website.html

    or:

    function lang($phrase){
        static $lang = array(
            'NO_PHOTO' => 'No photo\'s available',
            'NEW_MEMBER' => 'This user is new'
        );
        return $lang[$phrase];
    }
    
    echo lang('no_photo');
    

    (from: Most efficient way to do language file in PHP?)

    Without reinventing the wheel: http://php.net/gettext

    Or with javascript: Best practice javascript and multilanguage

    If you use some framework (either PHP or javascript) they usually have their own multilanguage supoort (laravel, angular, zend...)

    Hope it helps!