Custom HTMX directory

Estimated reading: 2 minutes

HTMX actions are registered for twig template files that reside in any of the default directories or custom directories. By default it will try to find twig templates that have the TemplateType: htmx header added in the following locations:

  • Your active theme or child-theme /views folder
  • Your Twig Template CPTs, If you’ve activated the Twig Template CPT to edit them from the dashboard.

Additionally, you can register custom paths so that you can add twig templates in custom plugins. To do that you only need to add two filter hook in your plugin, snippet manager or functions.php file:

add_filter( 'toolbox/htmx_dirs'             , 'register_custom_htmx_path' , 10 , 1 );
add_filter( 'toolbox_twig_views_locations'  , 'register_custom_htmx_path' , 10 , 1 );

/*
 * add a path to look for htmx files
 */
function register_custom_htmx_path( $paths ) {

  $paths = array_merge( $paths , [ YOUR_PLUGIN_DIR . '/twig-templates' ] );
  
  return $paths;
}

Please note that the code snippet above uses the same callback to register both the toolbox/htmx_dirs to search for htmx action calls, and uses to toolbox_twig_views_locations filter to register the path so that the twig templates can be used include, block, macro or extend any other valid template.

Additional resource

On top of the hooks mentioned above, there is another useful hook that can be added. This hook, timber/loader/loader can be used to add a so-called twig-namespace. Using a namespace you can target a specific views location directly, making sure you don’t accidentally use a copy in another path instead. Because you can add multiple paths, twig will try to find the first resource that matches the relative path. Using the namespace this is not the case.

add_filter( 'timber/loader/loader' , 'add_twig_namespace' );
/**
 * Add a namespace to the loader so that we can load templates
 * that are specific to our plugin
 */
function add_twig_namespace( $loader ) {

    $loader->addPath( YOUR_PLUGIN_DIR. 'twig-templates/' , 'myplugin' );

    return $loader;
} 

After doing this you can include your template using the namespace:

{# 
  include the twig template that resides 
    in the YOUR_PLUGIN_DIR . 'twig-templates/subdirectory' folder 
#}
{% include '@myplugin/subdirectory/posts-archive.twig' %}
Share this Doc

Custom HTMX directory

Or copy link

CONTENTS