Search code examples
flaskhtmx

Can htmx open another page and trigger an hx-swap into an hx-target on that page?


This is my first question so please tell me if I'm doing anything wrong:

Using htmx, how can I open another page and trigger an htmx swap into a target on that page?

I have a page "resources.html"

That page has an hx-target, a tbody,

#display-a-or-b

"A" is loaded automatically into the tbody because the hx-trigger for "A" is load, click.

<button 
    hx-get="/data-for-a"
    hx-target="#display-a-or-b" 
    hx-trigger="load, click" 
    hx-swap="innerHTML">
        Filling this with A
</button>
    <tbody id="display-a-or-b">
    </tbody>

Ihere is a second button to load "B"

<button 
    hx-get="/data-for-b"
    hx-target="#display-a-or-b" 
    hx-trigger="click" 
    hx-swap="innerHTML">
        Filling this with B
</button>

This is a flask app.

Here's the problem: I have a second page "newsletters.html"

I want to have a link on that page, that takes the user to the page "resources.html" but which fills the tbody "display-a-or-b" with "data-for-b"

However, the defaut fill is with "data-for-a" because the trigger for that is load, click.

Is it possible in htmx to open "resources.html" from a link on "newsletters.html" and at the same time fill the hx-target at "resources.html#display-a-or-b" with "data-for-b" rather than the default load of "data-for-a"?

Thanks very much.

The closest I could come up with as an htmx newbie is this:

Button on newsletter.html

<button 
    hx-get="/data-for-b"
    hx-target="resources.html#display-a-or-b" 
    hx-trigger="click" 
    hx-swap="innerHTML">
        Filling this with B
</button>

There is no response to my click.

I understand that there is such a thing as HX-Redirect, but how can I do a redirect to a new page and a swap to that page also?

The examples I have read have to do with code and response headers, that do not seem to be relevant.


Solution

  • If you are using Flask, an easy way to do this would be to use jinja to help.

    <!-- resources.html -->
    <button 
    hx-get="/{{ link }}"
    hx-target="#display" 
    hx-trigger="click" 
    hx-swap="innerHTML">
        # button text
    </button>
    

    and then in your views you can load the page based on the parameter:

    # resources route
    @app.route('/')
    def index():
        data_asked = request.args.get('data_asked', 'a')
        if data_asked== 'b':
            link = 'data_for_b'
        else:
            link = 'data_for_a'
        return render_template('resources.html', link=link)
    

    when you call it by default with no arguments, it will load the hx-get tag as /data_for_a. If you want to call it as /data_for_b, you simply pass a GET parameter in you newsletter page when calling the route (?data=b).

    There are more than one way to implement this, but the logic remains. Let me know if this response was helpful and if it worked well for you!