Search code examples
thymeleafhtmxspring-thymeleafhyperscript

How can I get Thymeleaf to work with Hyperscript dynamically?


I have a section of HTML that is being generated by a collection using Thymeleaf.

I can iterate over the collection just fine but the issue is when I try and get Hyperscript to see the Thymeleaf variables.

For example:

        <card-form class="hidden" th:id="'new-card-form-' + ${board.id}">
            <form action="#" class="flex flex-col gap-2">
                <textarea class="textarea" placeholder="Enter title..."></textarea>
                <div class="w-full">
                    <button class="bg-sky-700 px-2 py-1 rounded-lg font-bold hover:bg-sky-600 active:scale-95"
                            hx-post="/boards">Save Card</button>
                    <button class="bg-gray-600 px-2 py-1 rounded-lg hover:bg-gray-700 active:scale-95"
                            _="on click hide #new-card-form-${board.id} then show #board-footer-${board.id}">Cancel</button>
                </div>
            </form>
        </card-form>

Notice that I generate a custom "card-form" element with an id of th:id="'new-card-form-' + ${board.id}" This works as expected. The board.id is a UUID that gets passed along from the outer collection.

The issue is I don't know how to get Hypertext to recognize this ID.

The Hypertext code is:

_="on click hide #new-card-form-${board.id} then show #board-footer-${board.id}"

The "${board.id}" is being interpreted as a literal string.

How can I get Thymeleaf to inject that ID the way I expect?

Thanks


Solution

  • This should do the trick:

    th:_="|on click hide #new-card-form-${board.id} then show #board-footer-${board.id}|"
    

    Thymeleaf allows to use th: prefix even for things it does not know and it will still process the attribute correctly. If you combine it with the correct string concatenation then it should work.