[Thymeleaf] SpringEL, 지역변수 with

Kade Jeon·2024년 2월 8일
0

Thymeleaf

목록 보기
4/22

Spring EL

JSP의 EL과 기능이 유사하다. Model에서 객체(Object), List, Map 등의 형태로 넘겨주었을 때, 해당 객체에 접근하여 값을 꺼내올 수 있도록 한다.

아래 설명을 진행하기 위해서 아래와 같은 객체가 있다고 가정한다.


public class user(){
	private int username
	private int age
    
    public User(String username, int age){
    	this.username = username;
        this.age = age;
    }
}

Object에 접근

컨트롤러에서 Model에 객체를 담아 내보낸 경우, Html에서 SpringEL을 활용하여 접근하여 값을 꺼낼 수 있다.

<span th:text="${user.username}"></span>
<span th:text="${user['username']}"></span>
<span th:text="${user.getUsername}"></span>

List에 접근

컨트롤러에서 Model에 users라는 list를 담아 내보낸 경우, n번째 인덱스에 있는 객체의 username을 꺼낸다.

<span th:text="${users[0].username}"></span>
<span th:text="${users[0]['username']}"></span>
<span th:text="${users[0].getUsername()}"></span>

Map에 접근

컨트롤러에서 Model에 userMap이라는 Map을 담아 내보낸 경우, 해당 Map의 Key를 이용하여 Value를 꺼낸다.

<span th:text="${userMap['userA'].username}"></span>
<span th:text="${userMap['userA']['username']}"></span>
<span th:text="${userMap['userA'].getUsername()}"></span>

지역변수 활용

html의 태그 내(스코프 내)에서만 활용할 지역변수를 th:with 를 이용해 선언하여 사용할 수 있다.

아래 코드는 list에서 가장 첫 번째인 0번째 인덱스의 사람을 first라는 변수로 지정하고 활용한다. 이 경우에는 <div> 태그에 선언되었기 때문에 이 밖에서는(스코프 밖에서는) 사용할 수 없다.

<div th:with="first=${users[0]}">
  <p>first(첫번째) 사람은 <span th:text="${first.username}"> 입니다. </span></p>
</div>
profile
안녕하세요. 백엔드 개발자가 되고 싶은 Kade 입니다.

0개의 댓글