Created
April 15, 2015 15:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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