Skip to content

Instantly share code, notes, and snippets.

@marknotton
Created June 2, 2023 13:03
Show Gist options
  • Save marknotton/ed926e9a985ce26ed852ab3d516e547a to your computer and use it in GitHub Desktop.
Save marknotton/ed926e9a985ce26ed852ab3d516e547a to your computer and use it in GitHub Desktop.
Add a template path to any location, includes plugins/modules as well as the native templates directory
<?php
namespace yellostudio\helpers;
use Craft;
use craft\base\Plugin;
use yii\base\Event;
use craft\web\View;
use craft\events\RegisterTemplateRootsEvent;
class Helpers extends Plugin {
public static Helpers $plugin;
public function init(): void
{
parent::init();
self::$plugin = $this;
Craft::setAlias('@helpers', $this->getBasePath());
if ( getenv('CRAFT_ENVIRONMENT') == 'dev' ) {
Event::on(View::class, View::EVENT_REGISTER_SITE_TEMPLATE_ROOTS, function (RegisterTemplateRootsEvent $event) {
$event->roots['helpers'] = Craft::getAlias('@helpers/templates');
});
}
}
}
@marknotton
Copy link
Author

marknotton commented Jun 2, 2023

{{ include('helpers/foo') }}

Will now look for a foo.twig file in /vendor/yellostudio/helpers/src/templates/foo.twig. If the file doesn't exist, it will then fallback to the standard /templates/helpers/foo.twig file.

This prevents the need to do something like this:

$oldMode = \Craft::$app->view->getTemplateMode();
Craft::$app->view->setTemplateMode(View::TEMPLATE_MODE_CP);
$html = \Craft::$app->view->renderTemplate('plugin-handle/path/to/template');
Craft::$app->view->setTemplateMode($oldMode);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment