티스토리 뷰

비교적 최근에 나온 기술답게 thymeleaf 도 메뉴얼이 아주 훌륭하다. 

 

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a

www.thymeleaf.org

 

거의 모든 내용은 이 안에서 찾을 수 있다. 영어만 잘 하면 정말 훌륭한 개발자가 될수 있을것 같은데.. 

SI 특성상 빠르게 익히고 적용해야 하는데 이걸 다 읽고 있을 시간은 없다. 간단하게 자주 사용되는 부분만 추려서 보도록 하자. 


Thymeleaf Standard Expression

  • 변수 표현식 : ${...}
  • 선택 변수 표현식 : *{...}
  • 메시지 표현식 : #{...}
  • Link URL 표현식 : @{...}
  • Fragment Expressions : ~{...}

 

일단 가장 핵심적인 부분은 이 부분이다. 표준 표현식인데 다른 template engine 과 유사하다. 간단한 샘플을 만들어 보았다. 

 

fruit.html (Controller는 여기를 참조) 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>thymeleaf sample</title>
</head>
<body>
	${...} 변수 표현식 <br/>
	<span th:text="${fruit.fruit1}"></span><br/>
	<span th:text="${fruit.fruit2}"></span><br/>
	<span th:text="${fruit.fruit3}"></span><br/><br/>
	
	${...} 선택변수 표현식 <br/>
	<div th:object="${fruit}">
	    <span th:text="*{fruit1}"></span><br/>
	    <span th:text="*{fruit2}"></span><br/>
	    <span th:text="*{fruit3}"></span><br/><br/>
	</div>
	
	#{...} 메세지 표현식 <br/>
	<span th:text="#{FRUIT.FRUIT4}"></span><br/><br/>
	
	@{...} 링크 URL 표현식 <br/>
	<a th:href="@{http://www.naver.com}">naver</a><br/><br/>
	
	~{...} fragment 표현식<br/>
	<div th:insert="~{common/footer :: samplefooter}"></div>
	
</body>
</html>

 

위에 나온 표준 표현식을 골고루 써봤다. ${...} 과 *{...} 은 넘어온 데이터에 대해서 처리해주는 것이고 #{...} 이것은 해당 message가 있으면 출력해주고 아니면 key값을 그대로 반환해준다. 필자는 fruit.properties 라는 message 파일이 있고 이 안에는 FRUIT.FRUIT4=melon 라는 값이 들어있다. @{...}는 말 그대로 절대경로든 상대경로든 링크를 해준다. ~{...} 이녀석은 다른곳에 정의해 놓은 내용을 가지고 올때 사용을 하는것이라고 생각하면 된다. 가지고 올때는 th:insert, th:replace 등을 통해 가지고 올수 있다.

 

위의 예를 통해 fragment를 조금 더 살펴보면 실제 common/footer.html 파일이 있고 이 안에는 samplefooter 라는 fragment가 존재한다. 이 fragment를 가지고 와서 fruit.html 안에 넣어주는 것이라고 생각하면 된다. 

 

footer.html

 

application을 실행시키고 localhost:8080/fruit 으로 확인을 해보면 다음과 같은 결과를 얻을 수 있다. 

 

 

이런식으로 기존에 JSP에서 spring tag, JSTL tag, EL 표현식 등을 사용해서 구현했던 부분들을 thymeleaf를 통해 구현할 수 있다. 


Thymeleaf Attributes Value

th:abbr th:accept th:accept-charset
th:accesskey th:action th:align
th:alt th:archive th:audio
th:autocomplete th:axis th:background
th:bgcolor th:border th:cellpadding
th:cellspacing th:challenge th:charset
th:cite th:class th:classid
th:codebase th:codetype th:cols
th:colspan th:compact th:content
th:contenteditable th:contextmenu th:data
th:datetime th:dir th:draggable
th:dropzone th:enctype th:for
th:form th:formaction th:formenctype
th:formmethod th:formtarget th:fragment
th:frame th:frameborder th:headers
th:height th:high th:href
th:hreflang th:hspace th:http-equiv
th:icon th:id th:inline
th:keytype th:kind th:label
th:lang th:list th:longdesc
th:low th:manifest th:marginheight
th:marginwidth th:max th:maxlength
th:media th:method th:min
th:name th:onabort th:onafterprint
th:onbeforeprint th:onbeforeunload th:onblur
th:oncanplay th:oncanplaythrough th:onchange
th:onclick th:oncontextmenu th:ondblclick
th:ondrag th:ondragend th:ondragenter
th:ondragleave th:ondragover th:ondragstart
th:ondrop th:ondurationchange th:onemptied
th:onended th:onerror th:onfocus
th:onformchange th:onforminput th:onhashchange
th:oninput th:oninvalid th:onkeydown
th:onkeypress th:onkeyup th:onload
th:onloadeddata th:onloadedmetadata th:onloadstart
th:onmessage th:onmousedown th:onmousemove
th:onmouseout th:onmouseover th:onmouseup
th:onmousewheel th:onoffline th:ononline
th:onpause th:onplay th:onplaying
th:onpopstate th:onprogress th:onratechange
th:onreadystatechange th:onredo th:onreset
th:onresize th:onscroll th:onseeked
th:onseeking th:onselect th:onshow
th:onstalled th:onstorage th:onsubmit
th:onsuspend th:ontimeupdate th:onundo
th:onunload th:onvolumechange th:onwaiting
th:optimum th:pattern th:placeholder
th:poster th:preload th:radiogroup
th:rel th:rev th:rows
th:rowspan th:rules th:sandbox
th:scheme th:scope th:scrolling
th:size th:sizes th:span
th:spellcheck th:src th:srclang
th:standby th:start th:step
th:style th:summary th:tabindex
th:target th:title th:type
th:usemap th:value th:valuetype
th:vspace th:width th:wrap
th:xmlbase th:xmllang th:xmlspace

 

이게 다 뭔가? There are quite a lot of attributes like these, each of them targeting a specific HTML5 attribute 라고 공홈에 나와있다. 서버단에서 받은 데이터를 화면에 랜더링할때 위와 같이 th:xxxx 로 attribute 성격에 맞게 넣어주면 된다. 

 

자주 사용되는 필수 attribute 들은 다음과 같다. 

 

attribute desc 예제
th:text 텍스트 삽입 <span th:text="${fruit.fruit1}"></span>
th:utext HTML 삽입 <span th:utext="${fruit.fruit1}"></span>
th:value 값 삽입 <input type="hidden" id="sample" name="sample" th:value="${fruit.fruit1}"/>
th:with 변수값 지정 <p th:with="param1=xxx,param2=yyy"></p>
th:href 링크 삽입 <a th:href="@{http://www.naver.com}">naver</a>
th:if if 문 <div th:if="${fruit.fruit1} == 'apple'}">
th:unless else 문 <div th:unless="${fruit.fruit1} == 'apple'}">
th:attr 속성 추가 <label><input type="radio" name="sample" value="1" th:attr="checked='true'">예</label>
th:each 반복문 <option th:each="list, i : ${fruitList}" th:value="${list.getName()}" th:text="${list.getDesc()}"></option>

 

사용법은 무척 간단하다. 서버단에서 넘어온 데이터 표현할 부분에만 기존에 HTML5에서 쓰고 있던 attribute에 th: 만 붙여주면 된다. 


그럼 서버에서 넘어온 값을 javascript 변수로 받으려면?

 

<script th:inline="javascript">
  /*<![CDATA[*/
  var fruit = [[${fruit.fruit1}]];
  var defaultfruit = [[${#strings.defaultString(fruit.fruit1, 'watermelon')}]];
  /*]]>*/
</script>

 

이런 식으로 받아줄 수 있다. 이렇게 괄호를 많이 쓰는게 개인적으로는 조금 예쁘지는 않다고 생각된다.

strings.defaultString 이라는 것이 defaultfruit 정의하는 부분에 나오는데 이것은 Thymeleaf 에서 제공하는 Utility Object이다. 이것은 다음 장에서 다루도록 하겠다. 

 

끝!

 

 

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31