Advanced AJAX actions

Estimated reading: 4 minutes

Here you will find a few examples of more advanced AJAX action calls.

Pagination

A pretty simple pagination example is this one. Even though it’s a templatetype htmx, it can be used as the basis of subsequent ajax calls. By simply using an {% include 'yourtemplatename.twig' %} this will render the first 6 posts on page, with both above and under them pagination links that will replace the entire ID’s content with the AJAX request’s result.

A macro is used to be sure that the pagination above and below the posts is exactly the same.

{#
  TemplateType: htmx
  Action: get-posts
#}
 id="posts-archive">
    {%
    set args = {
        post_type: 'post',
        posts_per_page : 6,
        paged: request.get.page|default(1)
    }
    %}
    {% set posts = PostQuery( args ) %}
    {{ _self.pagination( posts ) }}
     class="uk-child-width-1-3@s uk-grid-match" uk-grid>
    {% for item in posts %}
    
class="uk-card uk-card-default uk-card-body">

{{ item.title }}

{{ item.preview().length(20) }}
{% endfor %}
{{ _self.pagination( posts ) }}
{% macro pagination( posts ) %} class="uk-flex uk-flex-center"> class="uk-pagination uk-margin-top" uk-margin> {% for page in posts.pagination.pages %}
  • href="#" hx-get="{{ ADMIN_AJAX_URL ~ '?' ~ { action: 'get-posts' , page : page.title }|build_query }}" hx-swap="outerHTML" hx-target="#posts-archive" class="{{ page.current ? 'uk-active' }}"> {{ page.title }}
  • {% endfor %}
    {% endmacro %}

    Banner rotator

    A very simple banner rotator can be created using a htmx call. In case of a real banner or image, it could get images from an array of URLs, an ACF gallery field or whatever comes to mind. This example replaces itself every 30 seconds and increments the variable ‘current_banner’ that is used to render a new number.

    Just like the previous template, this one can be added to a page using a {% include 'yourtemplatename.twig' %}.

    {#
        TemplateType: htmx
        Action: banner-rotate
    #}
     
        hx-get="{{ ADMIN_AJAX_URL ~ '?action=banner-rotate' }}"
        hx-swap="outerHTML"
        hx-trigger="load delay:30s">
        {# get the current banner number from the options table #}
        {% set current_banner = tb.get_option( 'htmx_current_banner' , 0 ) %}
         class="uk-text-center">
             class="uk-heading-small">This is banner #{{ current_banner }}
        
    {# update the number in the options table, use modulo to keep it below 5 #} {% set current_banner = tb.update_option( 'htmx_current_banner' , (current_banner + 1) % 5 ) %}