Multiple views in OctoberCMS component
In OctoberCMS we can easily override a component view to display datas in another way that in the original component.
But we can also add multiple views when we create it and use these views directly in the component’s parameters. Let’s see how.
In my last plugin, the Catalog, I thought it would be interesting for the user to be able to directly use multiple views instead of making his own override.
So, basically, first we have to add a parameter to the component like this :
Here we specify
menu_list as the default view, and place this parameter in a group to make things clean.
Then we need to create the
In the components folder I already have a
categories directory in which I have a file called
default.htm. This is the default content when I created the component with
php artisan create:component Tiipiik.Catalog Categories.
Let’s create the
menu_list.htm file, and inside add the code to display the menu as a list:
I’ve removed a lot of code to keep things clear.
Okay, now we have our file, but this is not really useful as the
default.htm file is still the one which will be used in the render of the page.
To make our page use the view we want, we have to rewrite the content of the
default.htm view like this :
And… that’s all ! :)
What does this code means ?
partial tels the system we want to load a partial file.
__SELF__ ~ "::" ~ __SELF__.render_view load the partials of this specific component directory with the name that is returned by the parameter.
We could also write
categories::categories.render_view but if another plugin uses a component named
categories it will make strange things.
In fact in this case you will have the content of the first component listed in the view of the second for example.
Now, if you want to add another view to your component, just create the file in the same directory and write your code inside.
Here is the essential part of the
image_list, the other view of my component to display categories as thumbnails:
So, one more time we can see that OctoberCMS is really flexible. You can write components views, give multiple views usable for users just by specifying the name of the desired view in the component parameter and you can also override each component view.
What do you want more ? :)