Setting the template path


January 27, 2022

Some components use the ts_load_more AJAX action hook, which is passed to a Twig template to render the output. For the hook to know which template-path to use, we need to set the template path using the twig_ajax_template_{$template} and twig_ajax_nopriv_template_{$template} hooks.

A simple example

For instance, let's assume that for your component that you're using a Twig template that normally you would be able to include as 'get-more-products.twig'.

In order to make this accessible to the ts_load_more action, you will need to add:

add_filter( 'twig_ajax_template_get-more-products' , function( $value ) { return 'get-more-products.twig'; }  );
add_filter( 'twig_ajax_nopriv_template_get-more-products' , function( $value ) { return 'get-more-products.twig'; }  );

If you've created Twig templates inside your theme's "views" directory or on a separate path you might have more complex Twig path locations, like:

add_filter( 'twig_ajax_template_get-more-products' , function( $value ) { return '@pluginnamespace/ajax/get-more-products.twig'; }  );
add_filter( 'twig_ajax_nopriv_template_get-more-products' , function( $value ) { return '@pluginnamespace/ajax/get-more-products.twig'; }  );

Using the filter, the ts_load_more action will be able to find the template path tracked by the template variable.

Used in a component's settings

Here's an example how this template would be used in the Pagination component:

{%- import 'components/generic/pagination.twig' as Pagination -%}
{{ Pagination.render( null, {
    container: 'prod-buttons',
    template: 'get-more-products',
    target: 'products-grid',
    current: posts.pagination.current,
    callbackdelay: 1000,
    posts_per_page: query.args.posts_per_page,
} ) }}