1. 개요

이 예제에서는 Thymeleaf 템플릿 에서 JavaScript 함수  를 호출할 것입니다.

의존성을 설정하는 것으로 시작하겠습니다. 그런 다음 Spring 컨트롤러와 Thymeleaf 템플릿을 추가합니다. 마지막으로 입력을 기반으로 JavaScript 함수를 호출하는 방법을 보여줍니다.

2. 설정

애플리케이션에서 Thymeleaf를 사용하기 위해 Maven 구성에 Thymeleaf Spring 5 의존성을 추가해 보겠습니다.

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

그런 다음 Student 모델 을 기반으로 Spring 컨트롤러에 이것을 추가해 보겠습니다 .

@Controller
public class FunctionCallController {

    @RequestMapping(value = "/function-call", method = RequestMethod.GET)
    public String getExampleHTML(Model model) {
        model.addAttribute("totalStudents", StudentUtils.buildStudents().size());
        model.addAttribute("student", StudentUtils.buildStudents().get(0));
        return "functionCall.html";
    }
}

마지막으로 src/main/webapp/WEB-INF/views 아래의 functionCall.html 템플릿에 이 두 JavaScript 함수를 추가합니다 .

AdChoices
광고
<script  th:inline="javascript">
    function greetWorld() {
        alert("hello world")
    }

    function salute(name) {
        alert("hello: " + name)
    }
</script>

이 두 함수를 사용하여 아래의 다음 섹션에서 예제를 설명합니다.

문제가 있으면 언제든지 Thymeleaf에 JavaScript를 추가하는 방법을 확인할 수 있습니다 .

3. Thymeleaf 내에서 JavaScript 함수 호출하기

3.1. 입력 없이 기능 사용하기

위의 welcomeWorld 함수 를 호출하는 방법은 다음과 같습니다 .

<button th:onclick="greetWorld()">using no variable</button>

모든 사용자 지정 또는 내장 JavaScript 함수에서 작동합니다.

3.2. 정적 입력과 함께 함수 사용

JavaScript 함수에 동적 변수가 필요하지 않은 경우 호출 방법은 다음과 같습니다.

AdChoices
광고
<button th:onclick="'alert(\'static variable used here.\');'">using static variable</button>

이것은 작은 따옴표를 이스케이프하고 SpringEL 이 필요하지 않습니다 .

3.3. 동적 입력과 함께 함수 사용

변수를 사용하여 JavaScript 함수를 호출하는 네 가지 방식이 있습니다.

변수를 삽입하는 첫 번째 방법은 인라인 변수를 사용하는 것입니다.

<button th:onclick="'alert(\'There are exactly '  + ${totalStudents} +  ' students\');'">using inline dynamic variable</button>

또 다른 옵션은 javascript:function 을 호출하는 것입니다 .

<button th:onclick="'javascript:alert(\'There are exactly ' + ${totalStudents} + ' students\');'">using javascript:function</button>

세 번째 방법은 데이터 속성 을 사용하는 것입니다 .

<button th:data-name="${student.name}" th:onclick="salute(this.getAttribute('data-name'))">using data attribute</button>

이 메서드는 onClickonLoad 와 같은 JavaScript 이벤트 를 호출할 때 유용합니다 .

마지막으로 이중 대괄호 구문으로 salute 함수를 호출할 수 있습니다 .

<button th:onclick="salute([[${student.name}]])">using double brackets</button>

이중 대괄호 사이의 표현식은 Thymeleaf 에서 인라인 표현식으로 간주됩니다 . 그렇기 때문에 th:text 속성에서도 유효한 모든 종류의 표현식을 사용할 수 있습니다.

4. 결론

이 예제에서는 Thymeleaf 템플릿에서 JavaScript 함수를 호출하는 방법을 배웠습니다. 의존성을 설정하는 것부터 시작했습니다. 그런 다음 컨트롤러와 템플릿을 구성했습니다. 마지막으로 Thymeleaf 내에서 JavaScript 함수를 호출하는 방법을 탐색했습니다.

항상 그렇듯이 코드는  GitHub에서 사용할 수 있습니다 .

Generic footer banner