Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Created April 28, 2019 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcaskill/f2269672cffe918e4f8899d7aafb5a71 to your computer and use it in GitHub Desktop.
Save mcaskill/f2269672cffe918e4f8899d7aafb5a71 to your computer and use it in GitHub Desktop.
Blade : Keep partials reusable with two presenter-style functions.

Blade Utilities

Two util functions to help keep blade partials reusable; props() passes on var $props as a casted object to the partial, and reduce() takes in an array of data and re-assigns/links keys (as seen in title), or just passes the key on as is (similar to ES6 destructuring).

— @withjacoby. (12 February 2019). https://twitter.com/withjacoby/status/1095248094214737921

Examples

@include('partials.comps.hero', App\props(
  App\reduce($hero, [
    'title' => 'hero_title',
    'editor',
    'image',
  ])
))
<?php
/**
* Convert array to an object recursively, a new instances of the stdClass.
*
* @param array $props The array to convert into an object.
* @return object
*/
function props(array $props) : object
{
return json_decode(json_encode($props));
}
<?php
/**
* Return the values of keys from the input array.
*
* @param array $input The array with master values to extract.
* @param array $keys The array keys to extract/reassign.
* @return array
*/
function reduce(array $input, array $keys) : array
{
$output = [];
foreach ($keys as $ka => $kb) {
if (is_string($kb)) {
if (is_int($ka)) {
$output[$kb] = $input[$kb] ?? null;
} elseif (is_string($ka)) {
$output[$kb] = $input[$ka] ?? null;
}
}
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment