Allow pages to be sorted by arbitrary meta values

This basically works like Pico's `sort_by` Twig filter
This commit is contained in:
Daniel Rudolf 2017-07-14 20:37:05 +02:00
parent b626782b87
commit 414f5ac18e
No known key found for this signature in database
GPG key ID: A061F02CD8DE4538
2 changed files with 28 additions and 3 deletions

View file

@ -25,7 +25,8 @@ twig_config:
#
date_format: %D %T # Pico's default date format
# See http://php.net/manual/en/function.strftime.php for more info
pages_order_by: alpha # Change how Pico sorts pages ("alpha" for alphabetical order, or "date")
pages_order_by_meta: author # Sort pages by meta value "author" (set "pages_order_by" to "meta")
pages_order_by: alpha # Change how Pico sorts pages ("alpha" for alphabetical order, "date", or "meta")
pages_order: asc # Sort pages in ascending ("asc") or descending ("desc") order
content_dir: content/ # The path to Pico's content directory
content_ext: .md # The file extension of your Markdown files

View file

@ -1509,7 +1509,7 @@ class Pico
$order = strtolower($this->getConfig('pages_order'));
$orderBy = strtolower($this->getConfig('pages_order_by'));
if (($orderBy !== 'date') && ($orderBy !== 'alpha')) {
if (($orderBy !== 'alpha') && ($orderBy !== 'date') && ($orderBy !== 'meta')) {
return;
}
@ -1525,7 +1525,31 @@ class Pico
return $cmp * (($order === 'desc') ? -1 : 1);
};
if ($orderBy === 'date') {
if ($orderBy === 'meta') {
// sort by arbitrary meta value
$orderByMeta = $this->getConfig('pages_order_by_meta');
uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order, $orderByMeta) {
$aSortValue = isset($a['meta'][$orderByMeta]) ? $a['meta'][$orderByMeta] : null;
$aSortValueNull = ($aSortValue === null);
$bSortValue = isset($b['meta'][$orderByMeta]) ? $b['meta'][$orderByMeta] : null;
$bSortValueNull = ($bSortValue === null);
$cmp = 0;
if ($aSortValueNull || $bSortValueNull) {
$cmp = ($aSortValueNull - $bSortValueNull);
} elseif ($aSortValue != $bSortValue) {
$cmp = ($aSortValue > $bSortValue) ? 1 : -1;
}
if ($cmp === 0) {
// never assume equality; fallback to alphabetical order
return $alphaSortClosure($a, $b);
}
return $cmp * (($order === 'desc') ? -1 : 1);
});
} elseif ($orderBy === 'date') {
// sort by date
uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order) {
if ($a['hidden'] xor $b['hidden']) {