makeitworkpress / wp-router

Enables developers to easily create custom routes with matching templates accordingly.
https://makeitwork.press/scripts/wp-router/
GNU General Public License v3.0
31 stars 6 forks source link

Feature request: Reusable templates #1

Open drewbaker opened 1 month ago

drewbaker commented 1 month ago

I'd love to be able to make templates reusable, and then also be able to get the name of the active template.

I think it can be done without a breaking change, and would make the router really really powerful!

So I could do something like this:

// router.php
$router = new MakeitWorkPress\WP_Router\Router( 
    [
        'film'        => ['route' => film/, 'template' => 'video.php'],
        'tv'           => ['route' => tv/, 'template' => 'video.php'],
        'music'    => ['route' => music/] // defaults to key as template name, so music.php        
    ], 
);
// video.php
if( get_current_route() == 'film' ) {
    // Some code unique to film route
}

This would make my templates more reusable, and allow me to keep my route based logic all based on the config in my router.php file.

leichim commented 1 month ago

Cool, that's a good suggestion, and I think it should already be possible (maybe with a very small change). Let me test it.

The current route can be retrieved by using get_query_var('template'), unless you specify a different query_var in the constructor of the Router..

drewbaker commented 1 month ago

I ended up taking this concept and making my own router for my use case. I don't need the permalink creation, as my templates will match to real pages/posts in WordPress. I also implemented Express style PathToRegex syntax so it's eay easier to handle more complex routes.

You can check it out here: https://github.com/drewbaker/wp-easy/blob/main/functions/libs/WpEasyRouter.php

<?php
/*
 * Define the templates to use, based on the valid WordPress routes.
 * 
 * Syntax is similar to Express paths in Node
 * The key is the route name, and the value is an array of [path, template]
 * If no template set, the key is used as the template name.
 * 
 * SEE https://github.com/gpolguere/path-to-regexp-php
 */

wp_easy_router([
    'home'              => ['path' => '/'],
    'work'              => ['path' => '/work/'],
    'work-detail'       => ['path' => '/work/:spot/', 'template' => 'work'],
    'reel'              => ['path' => '/reel/'],
]);