In trying to get a template to render from my plugin into the front-end, using this pattern:
use craft\web\View;
$oldMode = Craft::$app->view->getTemplateMode();
Craft::$app->view->setTemplateMode(View::TEMPLATE_MODE_CP);
$html = Craft::$app->view->renderTemplate('adminbar/src/templates/bar');
Craft::$app->view->setTemplateMode($oldMode);
Craft::dd($html);
This results in this error:
Twig Template Loading Error – craft\web\twig\TemplateLoaderException
Unable to find the template “adminbar/src/templates/bar”.
Please note: I've tried several variations of the path to my template and they all result in the same error
This is what worked for me to render a "CP" template from my service to the front-end.
<?php
namespace wbrowar\adminbar\services;
use wbrowar\adminbar\Plugin;
use Craft;
use craft\base\Component;
class AdminbarService extends Component
{
public function render(): string
{
$view = Craft::$app->getView();
$oldTemplatesPath = $view->getTemplatesPath();
$view->setTemplatesPath(Plugin::getInstance()->getBasePath());
$html = $view->renderTemplate('/bar');
$view->setTemplatesPath($oldTemplatesPath);
return $html;
}
}
@carlcs Thank you! I just had to add /templates to the path, but it worked:
$view = Craft::$app->getView();
$oldTemplatesPath = $view->getTemplatesPath();
$view->setTemplatesPath(AdminBar::getInstance()->getBasePath());
$html = $view->renderTemplate('/templates/bar');
$view->setTemplatesPath($oldTemplatesPath);
Craft::dd($html);
@brandonkelly From your perspective, is getTemplateMode() preferred over this method?
@wbrowar yes
@brandonkelly Okay, I'll update it when we figure out what's going on. If you want me to test anything out in the mean time or give you any more info, please let me know.
The fix works like a charm! Thanks @brandonkelly
$oldTemplateMode = $view->getTemplateMode();
$view->setTemplateMode($view::TEMPLATE_MODE_CP);
$html = $view->renderTemplate('adminbar/bar');
$view->setTemplateMode($oldTemplateMode);
return $html;
That does it. Thanks, guys!
Most helpful comment
@carlcs Thank you! I just had to add
/templatesto the path, but it worked:@brandonkelly From your perspective, is
getTemplateMode()preferred over this method?