2

In Craft 2, if you have a plugin that needs to load a view from the site templates directory, you could just go:

# Set the template context to site templates.
$path = craft()->path->getSiteTemplatesPath();
craft()->path->setTemplatesPath($path);

# Now we can load sweet templates from the sites templates dir, not the plugin one.
craft()->templates->render("/path/to/particular/site/template");

I'm struggling with doing this in a Craft 3 plugin. I thought I was on the right track with the below, but the context isn't updating.

# Set the template context to site templates.
$path = Craft::$app->getPath()->getSiteTemplatesPath();
Craft::$app->getView()->setTemplatesPath($path);

# Or this seems like it might do the same? 
# Craft::$app->getView()->setTemplateMode(View::TEMPLATE_MODE_SITE);

# Render the view!
Craft::$app->getView()->render("/path/to/particular/site/template")

This results in explosions. It shows the error:

Unable to resolve view file for view '/path/to/particular/site/template': no active view context.

Setting the template context is the bit that's not working. It's still looking at the plugin template directory.

5

Ok I've made sense of this - if you set the view template mode/context to site, then use the view renderTemplate() method (not render) it works.

So this is how you achieve the same thing in Craft 3.

# Set the template context to the site mode.
Craft::$app->getView()->setTemplateMode(View::TEMPLATE_MODE_SITE);

# Now using the renderTemplate() method, it will work.
$html = Craft::$app->getView()->renderTemplate("/path/to/particular/site/template");

Edit: Lenka commented pointing out there is actually some official documentation on this.

| improve this answer | |
0

This is a comment, but I'm a new participant, so I can't add it. I recommend the official documentation page https://docs.craftcms.com/v3/extend/updating-plugins.html#rendering-templates where you can find all the variants how to updating Rendering Templates from Craft2 to Craft3.

| improve this answer | |

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.