Skip to content

Template class

Javier Prieto edited this page Oct 12, 2021 · 3 revisions

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.


Generating a custom function for your plugin

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:

  1. {theme-folder}/my-plugin/blocks/header-alt.php
  2. {plugin-folder}/templates/blocks/header-alt.php
  3. {theme-folder}/my-plugin/blocks/header.php
  4. {plugin-folder}/templates/blocks/header.php.

See Also


Change log

Version Description
1.1.0 Introduced

Clone this wiki locally