October CMS resources and help articles

Simple and to the point. Optimized by the community.

Override a controller's view file locally in your plugin

8
by mjauvin, last modified on August 12th, 2019

Let's say you want to override a controller's view file (e.g. the Rainlab.Blog Posts controller):

  • copy the original view file into your plugin partials directory, under the posts folder.
  • modify the copied file to your liking
  • add the following code to the boot method of your Plugin registration file:
use Rainlab\Blog\Controllers\Posts;

public function boot()
{
    Posts::extend(function($controller) {
        list($author, $plugin) = explode('\\', strtolower(get_class()));
        $partials_path = sprintf('$/%s/%s/partials/posts', $author, $plugin);
        $controller->addViewPath($partials_path);
    });
}

Discussion

2 comments

1
larryb
Post on April 26th, 2019 7:31 PM

I use a similar override in some of my project, with one exception. I have found that Unix/Linux/Mac systems return class namespaces with \ instead of / which will produce errors on these machines. To fix this issue, I do a string replace on the path: $cleanPath = str_replace("\\", "/", $path);

-1
mjauvin
Post on October 27th, 2019 1:20 PM

I am on Linux and "/" works fine for class separators

We use cookies to measure the performance of this website. Do you want to accept these cookies?