xqllcw
Last Updated: November 25, 2018
·
508
· techmsi

Native php template helper function

Template helper for PHP

  • To assist in outputting arrays of data to a page, I used the native php heredocs, array_map, anonymous (Lambda) functions to create closures [introduced in PHP 5.3] & an output helper function.

Output Helper function

// If var not empty then return result otherwise return the var
$if = function ($var, $result = false) {
    return empty($var) ? false : ($result ? $result : $var);
};

Usage: Basic Example

<h1 class="name"><?= $if($single_details["title"]); ?></h2>

Usage: Advanced Example

<?= $if($group_social, $social_icons_markup($group_social)) ?>

// Render social item
$renderSocialItem = function ($outlet) {
    $type = $outlet["type"];
    $url = $outlet["url"];

     return <<< EOD
     <a class="{$type}" href="{$url}" target="_blank">
       <span class="icon"></span>
     </a>
EOD;
};

// Create a closure using anonymous function
$social_icons_markup = function ($group_social) use ($renderSocialItem) {
    return implode(array_map($renderSocialItem, $group_social));
};
?>