There are many different techniques used to add new templates via MyBB plugins. I’ve seen people building arrays within their plugin files, using XML files and more. In this post though, I will outline my current favourite way that makes use of standard HTML files and PluginLibrary along with PHP’s DirectoryIterator.
There are a few advantages to this in my opinion, though the two main ones are as follows:
- You write your templates in your text editor within a single HTML file for each one. This means your editor can provide syntax highlighting – making life much easier.
- You keep long winded HTML code out of your main plugin file meaning it is much easier to read.
The first thing to do to use this technique is to set up your directory structure within the ./inc/plugins folder as follows:
--inc
--plugins
--pluginName
--templates
// Template files will go here
// Any classes or other files for your plugin will go here
// Main plugin file will go here
As you can see, we have a folder named templates within a directory with the same name as our plugin. All of our templates will be stored in single HTML files within this directory.
Now all we have to do is iterate through that folder and store the contents of each template in an array for PluginLibrary to insert. This is where the DirectoryIterator comes in!
$dir = new DirectoryIterator(dirname(__FILE__).'/pluginName/templates'); // Change this to the path for your plugin
$templates = array();
foreach ($dir as $file) {
if (!$file->isDot() AND !$file->isDir() AND pathinfo($file->getFilename(), PATHINFO_EXTENSION) == 'html') {
$templates[$file->getBasename('.html')] = file_get_contents($file->getPathName());
}
}
$PL->templates(
'pluginname',
'pluginName',
$templates
);
As you can see from the above code, we define our path the templates are stored in then iterate through each file in the directory, adding its contents to an array. Pretty simple, eh?
Pingback: MyStatus MyBB plugin update inbound • euantor.com