Jump to content

Comparison template using URL segments


double
 Share

Recommended Posts

I am building a website with a structure like this:

  • Category1 (template compare)
    • Page 1 (template compare)
    • Page 2 (template compare)
    • Page 3 (template compare)
  • Category2
    • Page 4
    • Page 5

I want to create a comparison feature where, when visiting /category1/page1/, it will display the details of page1. But when navigating to /category1/page1/page2/, it will show both pages side by side for comparison.

I have added 404 error when the URL segment is incorrect, and also implemented redirection based on page IDs to prevent duplicates.

  1. Is this a good approach for building the comparison template?
  2. Should I change the URL structure to /category/page1-vs-page2/?
  3. What are the best practices for handling this kind of comparison feature in ProcessWire?

Here’s my code:

<?php
$segment = $input->urlSegment1;
// Comparison output
if (!empty($segment))
{
    echo "Segment has data: " . $segment;
    $page2 = $pages->getByPath('/category1/' . $segment);
    if (!$page2->id)
    {
        wire404();
    }
    if ($page2->id > $page->id)
    {
        $session->redirect('/category1/' . $page2->name . '/' . $page->name . '/');
        exit;
    }
    echo $page2;
}
//Category1 output
if ($page->id == 1041)
{
    echo "Category1";
}
// /category1/page/ output
else
{
    echo "Category1 child";
}

And here's -vs- comparison:

<?php
$segment = $input->urlSegment1;

if (!empty($segment)) {
    // Split the segment by '-vs-'
    $pagesToCompare = explode('-vs-', $segment);

    // Two pages to compare
    if (count($pagesToCompare) != 2 || empty($pagesToCompare[0]) || empty($pagesToCompare[1])) {
        wire404();
    }

    // The first and second page
    $page1 = $pages->getByPath('/category1/' . $pagesToCompare[0]);
    $page2 = $pages->getByPath('/category1/' . $pagesToCompare[1]);

    // If both pages exist
    if (!$page1->id || !$page2->id || $page1->id == 1041 || $page2->id == 1041) {
        wire404();
    }

    if ($page2->id > $page1->id)
    {
        $session->redirect('/category1/' . $page2->name . '-vs-' . $page1->name . '/');
        exit;
    }

    // Comparison here
    echo "<h1>Comparison of " . $page1->title . " vs " . $page2->title . "</h1>";

    return;
}


if ($page->id == 1041) {
    echo "Category1";
} else {
    echo "Category1 child";
}
?>

 

Edited by double
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...