Brain-WP / Cortex

Routing system for WordPress
MIT License
348 stars 20 forks source link

About template #17

Closed vittore closed 8 years ago

vittore commented 8 years ago

Hi,

I have done a simple plugin that use Cortex as routing system.

My plugin produce an html string that I need to render into default template.

add_action('wp_loaded', function () {
    Cortex::boot();
    add_action('cortex.routes', function (Route\RouteCollectionInterface $routes) {
        $routes->addRoute(new Route\QueryRoute(
            '{code:[A-Z]+}/myTest',
            function (array $matches) {
                $myObj = new myObj();
                $html=myObj->getHtml($matches['code']);

/** how to render template with $html ? **/                

            }
        ));
    });
});

What are correct steps?

Thanks in advance. v.

gmazzap commented 8 years ago

Hi @vittore

Cortex is just a routing library, how to render is actually up to you :)

If you use a QueryRoute like in your example, by default Cortex will let WordPress to choose template, which in your case ends up in loading index.php.

If you use the 'template' option of Cortex to force a specific template. E.g.

$routes->addRoute( new Route\QueryRoute(...), [ 'template' => 'my-template.php' ] );

Will make WordPress to load 'my-template.php' in theme or child theme.

This still leave you the isue how to pass variables... The WordPress way is to use globals

add_action('cortex.routes', function (Route\RouteCollectionInterface $routes) {
     $routes->addRoute(new Route\QueryRoute(
         function (array $matches) {
              $myObj = new myObj();
              global $my_html_string;
              $my_html_string = $myObj->getHtml($matches['code']);
         }
    }
});

and then in index.php:

global $my_html_string;
echo $my_html_string;

Another way would be to use WordPress filters:

add_action('cortex.routes', function (Route\RouteCollectionInterface $routes) {
     $routes->addRoute(new Route\QueryRoute(
         function (array $matches) {
              add_filter('my_custom_html', function() {
                    $myObj = new myObj();
                    return $myObj->getHtml($matches['code']);
              });
         }
    }
});

and then in index.php:

echo apply_filters('my_custom_html', '');

If you want to use something more "structured" you should setup something on your own... maybe use a template engine...

Cortex is a routing library, which means that allows you to set query variables from URL, maybe doing something custom when the route matches, but how to render template is out of its scope.

vittore commented 8 years ago

Thanks for your support. First solution (use of a global var into template) is my solution. Not best and clean, but it works perfectly. I close this issue.

v.