Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Block to add attributes to included fragments #981

Open
wimdeblauwe opened this issue Nov 24, 2023 · 1 comment
Open

Block to add attributes to included fragments #981

wimdeblauwe opened this issue Nov 24, 2023 · 1 comment

Comments

@wimdeblauwe
Copy link

I would like to have a block that allows to add extra attributes to the top-level element of an inserted or replaced fragment. I see 2 use cases for this:

  1. Inline SVG images where you want to add class attributes to style the SVG.
  2. When using htmx, you want to re-use the same fragment for an out-of-band swap. In that case, I would like to dynamically add hx-swap-oob="true" to the fragment when using it.

Example syntax

(The th:child-attrappend is obviously a first idea, we could iterate on a different/better name)

<th:child-attrappend hx-swap-oob="true">
  <div th:replace="~{fragments :: myfragment}"></div>
</th:child-attrappend>

If the myfragment looks like this:

<div th:fragment="myfragment">This is a fragment</div>

Then the rendered result should be:

<div hx-swap-oob="true">This is a fragment</div>

SVG example

With an SVG, it could be similar:

<th:child-attrappend class="h-4 w-4 text-red-500">
  <svg th:replace="~{info}"></svg>
</th:child-attrappend>

would render as:

<svg class="h-4 w-4 text-red-500" ...><path ...>
</svg>

Current alternative

I now use multiple almost identical fragments to work around this, but I would love to be able to avoid this.

@h4rk
Copy link

h4rk commented Dec 1, 2023

While working on an htmx + spring project myself, i run into the same need; while searching i found issue #716 which i belive asks for more or less the same thing. I think having a new attribute that mimics the replace but allows to add new attributes on top, as suggested in 716, would be a nice solution.

EDIT:
I should also add that at the moment as a workaround im running the following attribute on the fragment:
th:attr="hx-swap-oob=${isSwapOob!=null && isSwapOob}?true"
This way i am able to set a flag isSwapOob in the model and control the optional attribute when the template is rendered.

The use case i am looking for is being able to define a component only once and use it for the first load, the standard targeted swaps and oob swaps, without having to add the conditional attribute and specify the flag before every render.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants