4

This may be a bug...

I have a controller action which has been working great. It's a simple action with a single purpose... load a template with an internal value.

public function actionMyAction()
{
    $this->renderTemplate('myplugin/_mytemplate', array(
        'internalVar' => craft()->myPlugin->internalVar
    ));
}

When I call that action via a simple URL, everything loads flawlessly:

mywebsite.com/actions/myPlugin/myAction

Here's where it gets interesting...

So I just discovered the registerSiteRoutes hook. It looks awesome, and would make accessing my special page that much easier for a front-end user!

Here's how I implemented it in my MyPluginPlugin.php file:

public function registerSiteRoutes()
{
    return array(
        'myroute' => array('action' => 'myPlugin/myAction')
    );
}

The good news is, the route is properly followed, and my controller action gets loaded.

The bad news is, suddenly the template that's supposed to be loaded can't be found. :(

Template Error

Unable to find the template "myplugin/_mytemplate".

So does anyone know, what's going on here? I know that the renderTemplate method does some minor rewriting of the template path, but why would it be different when accessing via a front-end route?

7

Craft will only check for templates in your plugin’s templates/ folder during CP and action requests. When you start routing to your controller action via a site-facing route, it’s no longer either one of those; it’s just a normal Site request. So you will need to point Craft to your plugin’s templates folder explicitly.

// Point Craft to this plugin's templates/ folder
$templatesPath = craft()->path->getPluginsPath().'myplugin/templates/';
craft()->path->setTemplatesPath($templatesPath);

// Render and output the template
$this->renderTemplate('_mytemplate', $variables);

Note that it will no longer be necessary to include your plugin’s handle in the template path.

|improve this answer|||||
  • Minor typo in your solution, it should apparently be craft()->path->setTemplatesPath... Other than that, it worked perfectly! Thanks Brandon! – Lindsey D Jun 30 '14 at 18:38
  • Because I no longer need the plugin's handle in the template path, I also have to remove it from extends tags in the template. Which is fine, except when the layout I'm extending extends a layout from my main (non-plugin) templates. It now can't find that layout, because it's looking in my plugin templates. – Phil Gyford Sep 3 '15 at 10:48
  • @PhilGyford Yeah if you go this route, you can only include templates that live inside the directory passed into setTemplatesPath(). No way around that currently. – Brandon Kelly Sep 3 '15 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.