Recently, I ran into a problem whereby I needed to incorporate a magazine into a CraftCMS website that had been generated using a neat bit of software by the name of ‘FlipBuilder’. This would be a regular thing, so I was hoping I’d simply be able to drag and drop the outputted files into the templates folder and that it would magically work.
By default, anything in templates gets routed through CraftCMS’s templating engine which looks for images in the public folder. This was a problem for me as these magazines would be for logged in users only. If I put them in the public folder then any ‘Tom, Dick or Harry’ would be able to view them.
Thankfully, someone popped up with an idea that inspired me into a relatively simple solution, albeit by writing a custom plugin.
- To keep the ‘index.html’ file of the magazines inside templates as per usual
- Store the other assets inside a private directory outside of the public folder
- Write a plugin that would look for requests to these files and serve them from the private place instead.
I began by wireframing the plugin; I created a new folder inside craft/plugins named ‘magazineassets’. Inside this folder I added another folder named ‘controllers’ and a file named ‘MagazineAssetsPlugin.php’.
Once this was written, I went into the website’s admin panel and enabled the plugin.
The method of interest here is the ‘registerSiteRoutes’ one. What this does is looks for any requests to members/magazine/[issue]/[folder]/[file] and ‘sends’ them to a controller that we haven’t written yet…
(stored inside the, earlier created, ‘controllers’ folder)
The method of interest here is the ‘actionGetMagAsset’ function which matches the ‘action’ that we are now routing to via the ‘registerSiteRoutes()’ plugin method.
There’s no doubt in my mind that there’s probably some fancy way of writing that path using some baked in CraftCMS methods but I a) wasn’t certain what they are and b) wanted to be very rigid and certain that I definitely had the right path.
The path begins using a config setting (at config/general.php) that I already had thanks to another plugin that I was already using followed by ‘/magazines/[issue]/[folder]/[file]’ (sound familiar?). The config is below but I guess I could have just as easily written it as if I didn’t have the config or didn’t want it…
My config/general.php file:
I then used Craft’s built in InputOutput helper class to display the file if it exists and tested via the front-end.
Boom! All working now. Assets are loaded from the files folder, my file structure is like this (simplified obviously):
Yeah, okay, but the magazine is still public!
Right you are, it took two seconds to fix that. Into craft/templates/members/magazine/july-2018/mag/index.html I went and simply added…
…to the top of the file (without the spaces between % and the curly braces)
I hope this post helps anyone who faces a similar conundrum.