Setting global language variables in multilingual Perch builds

All of the multilingual projects that I’ve built in Perch Runway use a structural branching technique (/en, /es,/fr etc) to display each language’s content. Having a $lang variable to identify the current branch is a key part of the build and necessary for content localisation across many of the site templates.

The site structure

The top level of the site navigation will hold just the home pages for each language, and further levels of child pages can be added as required to each parent.

My current method for getting and storing the $lang variable uses the following in a global include.

    // Set empty variable
    $lang = '';

    // Check the first part of the current URL path and assign it to $lang_test variable
    $lang_test = explode('/', $_SERVER["REQUEST_URI"]);

    if (count($lang_test) > 1) {
        $lang_test = $lang_test[1];
    } else {
        $lang_test = '';

    // Get array of page info for the top level pages in our site (i.e. each language's home page)
    $langs = perch_pages_navigation(array(
        'from-path'            => '/',
        'levels'               => 1,
        'hide-extensions'      => false,
        'hide-default-doc'     => true,
        'flat'                 => true,
        'skip-template'        => true,
        'include-parent'       => true,
        'siblings'             => false,
        'only-expand-selected' => false,
        'add-trailing-slash'   => false,
        'navgroup'             => false,
        'include-hidden'       => false,
    ), true);

    // Loop through the array looking for a match on our $lang_test variable, setting $lang on a match
    foreach ($langs as $langobj) {
        if ($langobj['pagePath'] == '/' . $lang_test) {
            $lang = $lang_test;

    // Set default if no value assigned (i.e. no match found)
    if ($lang == '') {
        $lang = 'en';

    // Set language variable for use in Perch content templates

Language variable ready to go

The result is a $lang variable that I can use throughout the site templates help us localise correctly the content. It can also be useful to set locale information at this point.