mecha-cms / mecha

Minimalist content management system.
https://mecha-cms.com
GNU General Public License v3.0
175 stars 23 forks source link

Remove `$pager` and `$parent` Variable #165

Closed taufik-nurrohman closed 2 years ago

taufik-nurrohman commented 2 years ago

Use dynamic property feature to generate $page->next, $page->parent and $page->prev properties. These properties, if available, will contains a Page instance:

<?php if ($page->parent): ?>
  <nav class="pager">
    <?php if ($next = $page->next): ?>
      <a href="<?= $next->url; ?>" rel="next">
        <?= i('Next'); ?>
      </a>
    <?php endif; ?>
    <?php if ($prev = $page->prev): ?>
      <a href="<?= $prev->url; ?>" rel="prev">
        <?= i('Previous'); ?>
      </a>
    <?php endif; ?>
  </nav>
<?php endif; ?>

For “pages” mode, we will use link in place of url because URL that ends with numbers usually isn’t a page file (or not related directly to a page file):

<?php if ($next = $page->next): ?>
  <a href="<?= $next->link; ?>" rel="next">
    <?= i('Next'); ?>
  </a>
<?php endif; ?>

To assign custom page property directly to the current page instance:

$page->next = new Page('.\path\to\file.page');
$page->set('next', new Page('.\path\to\file.page'));

To assign custom page property globally to any page instance:

function get_next_page_path($current) { … }

Page::_('next', function() {
    $next = get_next_page_path($this->path);
    return $next ? new Page($next) : null;
});
function get_next_page_path($current) { … }

Hook::set('page.next', function() {
    $next = get_next_page_path($this->path);
    return $next ? new Page($next) : null;
});
taufik-nurrohman commented 2 years ago

Not possible to remove $pager safely because the $page variable likely will be overriden by the temporary variable of $pages’s item after foreach:

echo $page->next->link; // Referenced from the `$GLOBALS['page']` :)

foreach ($pages as $page) {
    echo $page->title; // This `$page` variable is no longer referenced to the `$GLOBALS['page']`
}

echo $page->next->link; // Overriden :(