HTMX TIP

공부는 혼자하는 거·2024년 5월 26일
0

환경

목록 보기
24/24

hx-confirm

무언가 삭제 요청할때, 쓰기 좋다.

Loading 표시

<body>
  <h1>HTMX Tutorial</h1>
  <button hx-get="/greeting" hx-target="#here" hx-indicator="#indicator">
    Click
  </button>
  <span class="htmx-indicator" id="indicator">Loading...</span>
  <h2 id="here">Here</h2>
</body>

페이지가 열리자마자 실행되는 코드 작성하기

hx-trigger='load'

예시

toggle button using htmx

HTMX multi-swap Extension

<script src="https://unpkg.com/htmx.org@1.9.12/dist/ext/multi-swap.js"></script>

HTMX Request인지 일반 Request인지 구분방법

Hx-Retarget, HX-Reswap

서버에서 요청에 대해 성공인지 exception인지 따라 다른 ui 조각을 던져줄 때, 이 옵션을 사용할 수 있겠다.

아니면 아래와 같은 extension도 있다.

https://htmx.org/extensions/response-targets/

만약 400~500 Http status를 그대로 유지하면서 에러 응답을 던져주고 싶다면, custom event listner를 활용할 수도 있다.

document.addEventListener('htmx:afterRequest', e => {
    if (!e.detail.xhr.status.toString().startsWith('2')) {
        let errorBanner = document.getElementById("toast");
        errorBanner.innerHTML = e.detail.xhr.responseText;
        errorBanner.style.display = 'block';
    }
});

HTMX on 속성

    attributes["hx-on--after-request"] = "javascript:document.getElementById('converter-input').value='';"

여러가지 간단한 자바스크립트 인라인 수행할 때 쓰기 좋다.

HTMX TAB

공식 사이트에서는 아래 2가지 방법을 제안하고 있다.

https://htmx.org/examples/tabs-javascript/
https://htmx.org/examples/tabs-hateoas/

나는 JS를 활용하는 방법을 선호한다.

fun DIV.tabView(
    category: String,
    activeCategory: String
) {
    val categoryTabId = "#category-tab-${category.removeSpecialCharacters()}"
    val activeCategoryTabId = "#category-tab-${activeCategory.removeSpecialCharacters()}"

    div {
        a {
            id = "$categoryTabId"
            classes = setOf("cursor-pointer", "tab", "tab-lifted", "m-tab")
            attributes["hx-get"] = "/table/${category}"
            attributes["hx-target"] = "#category-table"
            //attributes["onclick"] = "showActive('${category.removeSpecialCharacters()}')"
            if (categoryTabId == activeCategoryTabId) {
                classes += "tab-active"
            }
            attributes["hx-on:htmx-after-on-load"] =
                """
                   let currentTab = document.querySelector('.tab-active');                 
                   currentTab.classList.remove('tab-active')
                   let newTab = event.target                  
                   newTab.classList.add('tab-active')                            
                """.trimIndent()

            +"$category"
        }
    }
}

HTMX POST 요청을 JSON으로 보내면서 HTML로 응답받고 싶을 때

<script>
   const email = "htmxceo@x.com";
  const password = "htmxrocks";
</script>

...

<button hx-post="http://localhost:1330/login"
        hx-vals='js:{
        "userEmail": email
        "userPassword": password
    }'>
    Submit
</button>

Global Interceptor

document.addEventListener('htmx:configRequest', function(evt) {
    //evt.detail.headers['Authentication'] = "전달자: " + getJWT()
    evt.detail.headers['testHeader'] = "test"
});

Server에서 보낸 변수를 client 사이드에서 받고 싶을 때

htmx tip이라기보다 서버측 템플릿을 쓸 시 일반적인 서버와 클라이언트 간의 데이터 교환방법에 대한 TIP. 나 같은 경우 주로 아래와 같은 방법 씀.

// 서버 쯕 템플릿
        input {
            type = InputType.hidden
            value = "${post?.id ?: 0}"
            name = "postId"
        }
// 클라이언트 사이드
    let postId = document.querySelector('input[name=postId]').value;

참고

HTMX 요청으로 데이터 전송(3가지 방법)

최근 가장 핫한 HTMX 간결하게 살펴보기

htmx에는 JavaScript API가 있습니다. btw

htmx examples

HTMX, Thymeleaf 및 Spring Boot를 사용한 Toast

HTMX 사용 시 요청 오류 표시

HTMX + 3rd Party Libraries The Easy Way.

Htmx 마스터의 트릭

profile
시간대비효율

0개의 댓글