Skip to content

Instantly share code, notes, and snippets.

@selvinortiz
Created April 15, 2015 15:52
Show Gist options
  • Save selvinortiz/b71add608679cf65780a to your computer and use it in GitHub Desktop.
Save selvinortiz/b71add608679cf65780a to your computer and use it in GitHub Desktop.
Template rendering techniques used at https://selv.in/blog/rendering-templates-in-custom-locations
<?php
namespace Craft;
class MyPluginService extends BaseApplicationComponent
{
const DEFAULT_TEMPLATES_PATH = 'path/to/templates/';
/**
* Renders a template in a custom location defined by $path
*
* @param string $file
* @param array $vars
* @param string $path
*
* @return \Twig_Markup
*/
public function renderCustomTemplate($file, array $vars = array(), $path = self::DEFAULT_TEMPLATES_PATH)
{
$oldPath = craft()->path->getTemplatesPath();
craft()->path->setTemplatesPath($path);
$html = craft()->templates->render($file, $vars);
craft()->path->setTemplatesPath($oldPath);
return TemplateHelper::getRaw($html);
}
/**
* Renders the content of a template file using absolute path defined by $file
*
* @param string $file
* @param array $vars
*
* @throws Exception
* @return \Twig_Markup
*/
public function renderCustomTemplateString($file, array $vars = array())
{
if (is_readable($file))
{
$source = file_get_contents($file);
$rendered = craft()->templates->renderString($source, $vars);
return TemplateHelper::getRaw($rendered);
}
throw new Exception(Craft::t('{f} is missing or cannot be read.', array('f' => $file)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment