5

I'm new to Craft template development and one of the first things I'm trying to do is create a Variable that renders a template into the template its called from.

My directory structure looks like this:

/craft
  /plugins
    /test
      /templates
        _headers.html
      /variables
        TestVariable.php

Here is the Variable:

<?php

namespace Craft;

class TestVariable
{
    /**
     * Get header for test code
     *
     * @return string
     */
    public function headers()
    {
        return craft()->templates->render('test/_headers');
    }
}

And I'm calling it in the template with a simple: {{ craft.test.headers }}

My template is erroring with Unable to find the template “test/_headers”.

What am I misunderstanding here?

2
  • 1
    I ran into this issue yesterday, and I too am unsure of the answer. What I did find out is that when you try to render templates from the front-end, it looks to the front-end /templates directory for the Craft install, not the directory for your plugin. If there is a way to render templates from the plugin directory, I too would like to know. But looking through the code for a bit, I couldn't find a way to do it. Aug 14 '14 at 18:50
  • buildwithcraft.com/docs/plugins/templates is very unclear about where craft()->templates->render('test/_headers'); can be called from for plugins. It can definitely be called from the base plugin PHP, but beyond that I don't know.
    – cmal
    Aug 14 '14 at 22:01
5

Just added this note to the Plugin Templates documentation, which should answer your question:

Craft will only automatically look for templates within the plugin folders for CP requests. If you are going to be calling TemplatesService::render() from a front end site request, you will need to manually tell Craft where to find your template using PathService::setTemplatesPath() first:

$oldPath = craft()->path->getTemplatesPath();
$newPath = craft()->path->getPluginsPath().'pluginHandle/templates';
craft()->path->setTemplatesPath($newPath)
$html = craft()->templates->render('path/to/template');
craft()->path->setTemplatesPath($oldPath);

If you do this, you won’t be needing to begin the template path with your plugin handle.

1
  • Thanks, Brandon. I still couldn't get this code to work (Unable to find the template “_headers”.), and its a lot of code for what we're trying to accomplish, so I just included the entire template in the Variable as a string and used return craft()->templates->renderString($headerTemplateString); instead.
    – cmal
    Aug 15 '14 at 14: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.