백엔드 개발 Golang Go/Templ에서 깨끗하고 친숙한 Spinner 만들기

Go/Templ에서 깨끗하고 친숙한 Spinner 만들기

Sep 10, 2024 pm 06:30 PM

The unhelpful HTML

You guys might think that making a consistent, clean and professional spinbox would be a simple task in HTML... However, to our despair, there is no standard attrib to tell an input that it should only accept integer or decimal values, all input filtering must be JS. Outch!

I'm going to be implementing this functionality with Go, a-h/Templ, Tailwind and my beloved Alpine.js to make life easy.

Adding the Skeleton

We start by writing a basic template for our integer spinbox:

templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) {
  ...
}
로그인 후 복사

We define IntInterval as follows:

type IntInterval struct {
  A, B int
}
로그인 후 복사

With the interval, we will set min and max of the input. As we are making an integer spinbox, the step will always be set to '1'.

templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) {
  <input type="number" placeholder="Enter Int…"
    step="1"
    if interval != nil {
      min={ strconv.Itoa(interval.A) }
      max={ strconv.Itoa(interval.B) }
    } ...>
}
로그인 후 복사

Adding CSS

Let's now start adding some tw classes, following are some special properties and pseudo-elements that control the rendering of the input.
select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]

The following extra classes are used to remove the default spinner buttons:
[&::-webkit-inner-spin-button]:[-webkit-appearance:none] [&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]

Finally, let's add some basic padding, ring, colors, etc...
block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6

Adding it to our template, we get the following:

templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) {
  <input type="number" placeholder="Enter Int…"
    step="1"
    if interval != nil {
      min={ strconv.Itoa(interval.A) }
      max={ strconv.Itoa(interval.B) }
    }
    class="block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1
 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none
 focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6
 select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none]
 [-webkit-user-select:none] [&::-webkit-inner-spin-button]:[-webkit-appearance:none] 
[&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]">
}
로그인 후 복사

Now you should get a very text-like input, with some basic validation if you hover your mouse over it. We will add the functionality to check for valid integer inputs in the next section.

Implementing the Filter

The basic idea of an integer spinbox is of an input that only accepts integers. I initially attempted to implement this function by using HTML's pattern attribute as follows:

<input type="number" pattern="[0-9]+" ... >
로그인 후 복사

The pattern attribute takes a regex string and uses it to validate the user input, however, it doesn't prevent invalid input from being entered in the first place. Actually, it was made for some simple client-side validation.

The 'oninput' event

Every time the user presses any key inside the input box, a oninput event is generated. capture this event with Alpine's syntax x-on:input and rectify the value accordingly for the input element. Let's create a parent div with an x-data attrib set, and add a function that will allow us to check if input is at all a Number... After which we can round the value accordingly.

<div x-data="{isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }}">
  <input ... x-on:input="$el.value = isNumber($el.value) ? Math.round($el.value) : null">
</div>
로그인 후 복사

For those who don't know Alpine, $el here is used to refer to the current DOM element.

Custom Spinners

In the parent div created previously, we add the following class="flex" and add an x-ref="spinbox" attrib to the input so that our buttons can modify it's state through the magic property $refs.spinbox:

<div ... class="flex">
  <input ... x-ref="spinbox">
</div>
로그인 후 복사

We then add a new child after the input, which will contain our buttons:

<div ...>
  <input ... x-ref="spinbox">
  <div class="flex flex-col-reverse">
    <!-- Decrement input's value -->
    <button type="button" class="flex-1 ...">-</button>
    <!-- Increment input's value -->
    <button type="button" class="flex-1 ...">+</button>
  </div>
</div>
로그인 후 복사

Here, we use flex-col-reverse as an easy way to keep the tab order correct, it should first tab to '-', then '+'.

We then add the event handlers to the buttons using x-on:click, the full code (excluding CSS) is as follows:

<div ... x-data="{
        inc() { var e = $refs.spinbox; e.value = Math.min(Number(e.value) + Number(e.step), e.max); },
        dec() { var e = $refs.spinbox; e.value = Math.max(Number(e.value) - Number(e.step), e.min); },
        isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }
      }">
  <input ... x-ref="spinbox" x-on:input="$el.value = isNumber($el.value) ? Math.round($el.value) : null">
  <div ...>
    <!-- Decrement input's value -->
    <button type="button" ... x-on:click="dec">-</button>
    <!-- Increment input's value -->
    <button type="button" ... x-on:click="inc">+</button>
  </div>
</div>
로그인 후 복사

We have to convert e.value and e.step before doing any arithmetic as those are strings.

When it comes to CSS for the spinners buttons, they are styled very similarly to the input, the full code is below .

Making a Clean, friendly Spinner in Go/Templ

The final template

templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) {
  <!-- Disable inner & outer spinner buttons, use buttons to render increment and decrement input value... -->
  <div class="flex-1">
    @InputLabel(name, label + " " + interval.toString(), tooltip)

    <input type="number" placeholder="Enter Int…" step="1"
        if interval != nil {
          min={ strconv.Itoa(interval.A) } max={ strconv.Itoa(interval.B) }
        }
        name={ name } value={ value }
        class="block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1
 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none
 focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6
 select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none]
 [-webkit-user-select:none] [&::-webkit-inner-spin-button]:[-webkit-appearance:none] 
[&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]"
        x-on:input="$el.value = !isNumber($el.value) ? null : Math.round($el.value)"
        x-ref="spinbox"
        autocomplete="off"
        >

        <div class="flex flex-col-reverse font-medium">
          <!-- Decrement input's value -->
          <button type="button" class="flex-1 px-1 leading-none
 transition-colors ease-linear duration-100 rounded-br-md text-center
 text-sm bg-gray-100 hover:bg-gray-200 text-gray-500 hover:text-gray-900
 ring-1 ring-inset ring-gray-300 focus:outline-none focus:ring-inset
 focus:ring-2 focus:ring-primary-400 select-none [-moz-user-select:none]
 [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]" x-on:click="dec">-</button>
          <!-- Increment input's value -->
          <button type="button" class="flex-1 px-1 leading-none
 transition-colors ease-linear duration-100 rounded-tr-md text-center
 text-sm bg-gray-100 hover:bg-gray-200 text-gray-500 hover:text-gray-900
 ring-1 ring-inset ring-gray-300 focus:outline-none focus:ring-inset
 focus:ring-2 focus:ring-primary-400 select-none [-moz-user-select:none]
 [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]" x-on:click="inc">+</button>
        </div>
    </div>
  </div>
}
로그인 후 복사

Enjoy :)

Works on

  • Mozilla Firefox 130.0 (64-bit)
  • Version 128.0.6613.120 (Official Build) (64-bit)

위 내용은 Go/Templ에서 깨끗하고 친숙한 Spinner 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Debian Openssl의 취약점은 무엇입니까? Debian Openssl의 취약점은 무엇입니까? Apr 02, 2025 am 07:30 AM

보안 통신에 널리 사용되는 오픈 소스 라이브러리로서 OpenSSL은 암호화 알고리즘, 키 및 인증서 관리 기능을 제공합니다. 그러나 역사적 버전에는 알려진 보안 취약점이 있으며 그 중 일부는 매우 유해합니다. 이 기사는 데비안 시스템의 OpenSSL에 대한 일반적인 취약점 및 응답 측정에 중점을 둘 것입니다. DebianopensSL 알려진 취약점 : OpenSSL은 다음과 같은 몇 가지 심각한 취약점을 경험했습니다. 심장 출혈 ​​취약성 (CVE-2014-0160) :이 취약점은 OpenSSL 1.0.1 ~ 1.0.1F 및 1.0.2 ~ 1.0.2 베타 버전에 영향을 미칩니다. 공격자는이 취약점을 사용하여 암호화 키 등을 포함하여 서버에서 무단 읽기 민감한 정보를 사용할 수 있습니다.

프론트 엔드에서 백엔드 개발로 전환하면 Java 또는 Golang을 배우는 것이 더 유망합니까? 프론트 엔드에서 백엔드 개발로 전환하면 Java 또는 Golang을 배우는 것이 더 유망합니까? Apr 02, 2025 am 09:12 AM

백엔드 학습 경로 : 프론트 엔드에서 백엔드 초보자로서 프론트 엔드에서 백엔드까지의 탐사 여행은 프론트 엔드 개발에서 변화하는 백엔드 초보자로서 이미 Nodejs의 기초를 가지고 있습니다.

Beego ORM의 모델과 관련된 데이터베이스를 지정하는 방법은 무엇입니까? Beego ORM의 모델과 관련된 데이터베이스를 지정하는 방법은 무엇입니까? Apr 02, 2025 pm 03:54 PM

Beegoorm 프레임 워크에서 모델과 관련된 데이터베이스를 지정하는 방법은 무엇입니까? 많은 Beego 프로젝트에서는 여러 데이터베이스를 동시에 작동해야합니다. Beego를 사용할 때 ...

GO에서 플로팅 포인트 번호 작업에 어떤 라이브러리가 사용됩니까? GO에서 플로팅 포인트 번호 작업에 어떤 라이브러리가 사용됩니까? Apr 02, 2025 pm 02:06 PM

Go Language의 부동 소수점 번호 작동에 사용되는 라이브러리는 정확도를 보장하는 방법을 소개합니다.

Go 's Crawler Colly의 큐 스레드의 문제는 무엇입니까? Go 's Crawler Colly의 큐 스레드의 문제는 무엇입니까? Apr 02, 2025 pm 02:09 PM

Go Crawler Colly의 대기열 스레딩 문제는 Colly Crawler 라이브러리를 GO 언어로 사용하는 문제를 탐구합니다. � ...

골란드의 사용자 정의 구조 레이블이 표시되지 않으면 어떻게해야합니까? 골란드의 사용자 정의 구조 레이블이 표시되지 않으면 어떻게해야합니까? Apr 02, 2025 pm 05:09 PM

골란드의 사용자 정의 구조 레이블이 표시되지 않으면 어떻게해야합니까? Go Language 개발을 위해 Goland를 사용할 때 많은 개발자가 사용자 정의 구조 태그를 만날 것입니다 ...

이동 중에 왜 println 및 string () 함수로 문자열이 다른 효과를 갖는 이유는 무엇입니까? 이동 중에 왜 println 및 string () 함수로 문자열이 다른 효과를 갖는 이유는 무엇입니까? Apr 02, 2025 pm 02:03 PM

Go Language의 문자열 인쇄의 차이 : println 및 String () 함수 사용 효과의 차이가 진행 중입니다 ...

Redis Stream을 사용하여 GO Language에서 메시지 대기열을 구현할 때 User_ID 유형 변환 문제를 해결하는 방법은 무엇입니까? Redis Stream을 사용하여 GO Language에서 메시지 대기열을 구현할 때 User_ID 유형 변환 문제를 해결하는 방법은 무엇입니까? Apr 02, 2025 pm 04:54 PM

Go Language에서 메시지 대기열을 구현하기 위해 Redisstream을 사용하는 문제는 Go Language와 Redis를 사용하는 것입니다 ...

See all articles