4

I want to be able to render a template in the main 'templates' directory from within a plugin controller.

Basically the controller gets the url request, does some work and then renders a template saved in the 'craft/templates' directory instead of the 'plugin/templates' directory.

I have tried the plugin path trick mentioned on this page https://craftcms.com/docs/plugins/templates without any success.

Any ideas?

  • The trick on that page should do it for you. Can you var_dump the paths to make sure they are pointing to where you think they are pointing? – Brad Bell Oct 24 '14 at 22:15
  • The path echoes out where I would expect '/Users/derrick/Documents/wwwroot/iha/craft/templates/' however when I do $html = craft()->templates->render('test'); it always get a 404 page not found. I don't need an entry or route setup to the 'test' template correct? If I browser to local.site.com/test I see the test template. – Derrick Grigg Oct 24 '14 at 23:22
  • Digging a little more into this. If I pass a path for a template that doesn't exist I get an error message "Unable to find the template “_test”." However if pass a path for a template that does exist, I don't get that error message but I do get redirected to the 404, page not found. Does that make sense? Right now the template has no logic in just a little markup, there's nothing in it to redirect. Is there something that needs to get returned from the controller method to prevent a 404? – Derrick Grigg Oct 25 '14 at 16:57
  • Found the answer, you need to use the $this->renderTemplate() in the controller vs the craft()->templates->render(); – Derrick Grigg Oct 25 '14 at 16:59
  • @DerrickGrigg BaseController::renderTemplate() calls TemplatesService::render() internally. Guessing that you just happened to be triggering Craft from a site request when testing that theory. See my answer below. – Brandon Kelly Oct 28 '14 at 9:43
8

Craft will only serve templates from craft/templates/ by default if it’s a front-end site request.

To explicitly tell Craft to serve templates from there, you can use PathService::setTemplatesPath():

$path = craft()->path->getSiteTemplatesPath();
craft()->path->setTemplatesPath($path);

$this->renderTemplate('path/to/template', $variables);

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.