-
Notifications
You must be signed in to change notification settings - Fork 0
Template class
Important: This documentation is still under construction, methods and/or properties may be missing or not fully documented
The Template class is a helper that allows to generate an alternative to get_template_part in your plugin to get templates from your plugin template path and allow override in your theme.
For this guide we assumed that your plugin structure is similar to this
{plugin-folder}/
/my-plugin.php
/includes/
/general-template.php
/templates/
/blocks/
/header.php
/header-alt.php
And in your theme your have a structure to override one of the plugin's template
{theme-folder}/
/my-plugin/
/blocks/
/header-alt.php
In your plugin root file
<?php
// my-plugin.php
...
define('MY_PLUGIN_TEMPLATE_PATH', __DIR__ . '/templates')
include_once('includes/general-template.php')
...<?php
// general-template.php
use JPToolkit\TemplateHelper\Template;
/**
* @param string $slug The slug name for the generic template.
* @param string|null $name The name of the specialized template.
* @param array $args Additional arguments passed to the template.
*/
function my_plugin_get_template_part($slug, $name = null, $args = [])
{
static $template;
if (empty($template)) {
$template_path = MY_PLUGIN_TEMPLATE_PATH; // path of your template folder in your plugin
$stylesheet_path = 'my-plugin'; // path of your template folder in your theme
$namespace = 'my_plugin'; // optional, this is used to prefix actions
$template = new Template($template_path, $stylesheet_path, $namespace);
}
$template->get_template_part($slug, $name, $args);
}This function preserve all of functionality of get_template_part using the same parameters, for more details about the parameters please read this
<?php
// Example of use
my_plugin_get_template_part('blocks/header','alt')In this example the blocks/header-alt template is override in the theme because the function search the requested template in this order:
{theme-folder}/my-plugin/blocks/header-alt.php{plugin-folder}/templates/blocks/header-alt.php{theme-folder}/my-plugin/blocks/header.php-
{plugin-folder}/templates/blocks/header.php.
| Version | Description |
|---|---|
| 1.1.0 | Introduced |