Skip to content

Instantly share code, notes, and snippets.

@jesseleite
Created February 21, 2019 17:06
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 jesseleite/773b719ee3318affda58e40852467869 to your computer and use it in GitHub Desktop.
Save jesseleite/773b719ee3318affda58e40852467869 to your computer and use it in GitHub Desktop.
Statamic v2 array batch addon idea
{{ collection:blog as="posts" }}
<h3>Group 1</h3>
{{ posts scope="tag" array_batch.split="3" array_batch.select="1" }}
{{ partial:block }}
{{ /posts }}
<h3>Group 2</h3>
{{ posts scope="tag" array_batch.split="3" array_batch.select="2" }}
{{ partial:block }}
{{ /posts }}
<h3>Group 3</h3>
{{ posts scope="tag" array_batch.split="3" array_batch.select="3" }}
{{ partial:block }}
{{ /posts }}
{{ /collection:blog }}
<?php
namespace Statamic\Addons\ArrayBatch;
use Statamic\Extend\Modifier;
class SelectModifier extends Modifier
{
/**
* Modify a value
*
* @param mixed $value The value to be modified
* @param array $params Any parameters used in the modifier
* @param array $context Contextual values
* @return mixed
*/
public function index($value, $params, $context)
{
return $value[$params[0] - 1];
}
}
<?php
namespace Statamic\Addons\ArrayBatch;
use Statamic\Extend\Modifier;
class SplitModifier extends Modifier
{
/**
* Modify a value
*
* @param mixed $value The value to be modified
* @param array $params Any parameters used in the modifier
* @param array $context Contextual values
* @return mixed
*/
public function index($value, $params, $context)
{
return $this->split($value, $params[0]);
}
/**
* Logic from a newer version of \Illuminate\Support\Collection::split()
*
* @param array $value
* @param int $numberOfGroups
* @return static
*/
public function split($value, $numberOfGroups)
{
$collection = collect($value);
if ($collection->isEmpty()) {
return collect();
}
$groups = collect();
$groupSize = floor($collection->count() / $numberOfGroups);
$remain = $collection->count() % $numberOfGroups;
$start = 0;
for ($i = 0; $i < $numberOfGroups; $i++) {
$size = $groupSize;
if ($i < $remain) {
$size++;
}
if ($size) {
$groups->push(collect(array_slice($collection->all(), $start, $size)));
$start += $size;
}
}
return $groups;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment