wimdeblauwe / htmx-spring-boot

Spring Boot and Thymeleaf helpers for working with htmx
Apache License 2.0
423 stars 41 forks source link

Adding HtmxUtils for better reference in Templates #106

Open tschuehly opened 2 months ago

tschuehly commented 2 months ago

In every project I'm doing I create a HtmxUtil class, I think this improves template readability, and could start establishing good practices.

For example having a URI method to put variables into a constant:

  public static String URI(String uriTemplate, Object... variables) {
    return new UriTemplate(uriTemplate).expand(variables).toString();
  }

and then in the controller

  public static final String GET_EDIT_USER_MODAL = "/save-user/modal/{uuid}";

  @GetMapping(GET_EDIT_USER_MODAL)
  public ViewContext editUserModal(@PathVariable UUID uuid) {
    return editUserComponent.render(uuid);
  }

then in the template

        <button hx-get="${URI(GET_EDIT_USER_MODAL,uuid)}"
                hx-target="#${MODAL_CONTAINER_ID}">
            <img src="/edit.svg">
        </button>

Here's an example: https://github.com/tschuehly/htmx-spring-workshop/blob/lab-4/src/main/java/de/tschuehly/easy/spring/auth/htmx/HtmxUtil.java

wimdeblauwe commented 2 months ago

I personally don't really like having constants for the URL paths. I don't feel it improves the readability of the code as the function of a controller method is mapping a URL to a method, so I like to have my URL close to my method. Some might call it locality of behaviour ;-)

But if others feel this is useful, we could add this.

tschuehly commented 2 months ago

In a big project, it really helps finding where Controller Endpoints are used. Especially as you can browse around with CTRL + B between your templates and your Controllers in IntelliJ.

checketts commented 2 months ago

The constants are separate from the HtmxUtils discussion. I would expose the utils class as a bean then reference it via @util.uri() syntax. (That references Spring beans)

However, I haven't found a consistent use for it. So I would be interested to see the proposed methods.

tschuehly commented 2 months ago

The constants are separate from the HtmxUtils discussion. I would expose the utils class as a bean then reference it via @util.uri() syntax. (That references Spring beans)

Once again, I would stay with a complete static Util Class as we can use it with all template langauges

However, I haven't found a consistent use for it. So I would be interested to see the proposed methods.

I will clean one up and post it here,

landsman commented 1 month ago

I would love to see this utils, it make sense to me.