• Controller
@GetMapping("/m5")
	public String m5(Model model) {
		model.addAttribute("name", "age");
		model.addAttribute("size", 30);
		model.addAttribute("color", "cornflowerblue");
		return "m5";
}
  • HTML 속성조작
    • th:text="값"
    • th:HTML속성명="값"
    • 기존에 동일한 속성이 선언되어 있으면 대체한다.
    • 기존에 동일한 속성이 선언되어 있지 않으면 추가한다. 
    • ★ 대부분의 경우에는 서버에서 Model로 전송하여 받은 값은 그냥 사용할 수 없다. 
      • 직접 표현식으로 ${key} 형태로는 바로 못쓴다.(일반속성에 표현식 적용이 안된다.)
      • th:속성으로 표현식을 넣어야 가능하다. 
<div>${name}</div>
<div th:text="${name}"></div>

<input type="text" name="age">     <!-- 이건 정적 -->
<input type="text" th:name="age">  <!-- 이건 타임리프가 손을 대서 만듬 -->
<input type="text" name="${name}"> <!-- 이건 타임리프 속성이라 안된다. -->
<input type="text" th:name="${name}"> <!-- 이건 타임리프 속성이다. -->
<input type="text" th:name="${name}" th:size="${size}">  
<input type="text" th:value="${color}">
  • 위의 코드는 아래와 같이 해석된다. th:name="age" 이렇게 타임리프 속성에 정적인 값을 넣어도 적용이 되지만 일반 속성에 표현식을 넣으면 적용이 되지 않는다.

해석

 

  • th:class 
    • 특이한 점이 있다면 한번더 정의하게 되면 나중에 나온것이 적용이 된다. 
<div class="one">Box 1</div>
<div th:class="one">Box 2</div>
<div class="one" th:class="two">Box 3</div>

적용

  • 기존에 jquery 하던 class append 같은 것들을 하는 append 속성
    • th:attrappend > 뒤
    • th:attrprepend > 앞 
    • th:classappend > 뒤
<div class="one" th:attrappend="class=' two'">Box 4</div>
<div class="one" th:attrprepend="class='two '">Box 5</div>
<div class="one" th:classappend="two">Box 6</div>

결과

  • 속성 설정 및 css 스타일 설정
    • th:checked는 타임리프에 의해서 속성이 뭔가 새롭게 가공되는 느낌이다. 
      • true면 checked="checked", false면 아예 나타나지 않는다. 
    • th:style을 넣을 때는 그냥 맘 편하게 |  |을 사용하고 그렇게 쓰지 않으면 문자열 + 로 처리
<input type="checkbox" name="cb" th:checked="true">
<input type="checkbox" name="cb" th:checked="false">

<div th:style="'background-color:' +${color}">Box 7 </div> 
<div th:style="|background-color:${color}|">Box 7 </div>

결과

  • Controller
@GetMapping("/m6")
	public String m6(Model model) {
		String name = mapper.getTxt();
		BoardDTO dto = mapper.getDTO();
		String txt = "안녕하세요. &lt;i&gt;홍길동</i> 입니다.";
		int num = 100;
		List<String> names = mapper.getNames();
		model.addAttribute("name", name);
		model.addAttribute("dto", dto);
		model.addAttribute("txt", txt);
		model.addAttribute("num", num);
		model.addAttribute("names", names);
		return "m6";
}
  • getNames 부분의 쿼리정의 ↓
<select id="getNames" resultType="String">
    select first_name from employees where rownum &lt;= 10
</select>
  • th:text는 기본적으로 escape 되어 텍스트가 출력된다.
    • 해석이 안되고 escape 된다. > CDATA 느낌
  • th:utext 
    • unescaped text으고 PCDATA로 해석이 되어 출력이 된다. >> script injection이 된다.
<div th:text="${txt}"></div>
<!-- 이스케이프 되서 출력 -->
<div th:utext="${txt}"></div>
<!-- 이스케이프 안되서 출력 i태그도 나온다.-->

결과

  • th:inline
    • 1. th:inline="text" // html 쪽에서 쓴다. 사용 잘 안한다.
    • 2. th:inline="javascript" // script 쪽에서 쓴다. 많이 쓴다.(필수) ★★★★
  • escape text, unescape text를 태그 사이 내용으로 넣을 때 아래의 키워드를 쓴다. (th:inline이 함께 쓰이면서) 안쪽에 표현식을 넣는다. 
    • [[ ]] : escaped text
    • [( )] : unescaped text
    • ★★★ 이런 것들 주석처리는 타임리프 주석처리로 해야한다. <!-- --> 와 같은 일반주석 처리시에는 에러난다. 
    • <!--/*        주석할 내용            */--> 
    • <!--/* <div th:inline="text">[[${a}]] + [[${b}]] = [[${a + b}]]</div> */-->
<div th:inline="text">[[${name}]]</div>
<div th:inline="text">[(${name})]</div>

<div th:inline="text">[[${txt}]]</div>
<div th:inline="text">[(${txt})]</div>

<div>[(${txt})]</div>
<div th:inline="text">[[${num}]] + [[${num}]] = [[${num + num}]]</div>

결과

  • th:inline="javascript"를 쓴 것과 안쓴 것의 차이 ★
    • label1, label2에 값을 넣는 예제인데 기존에 표현식을 script 단에서 썼을 때 문자열 표현식을 '  '로 감싸야 했던 상황이 있었는데 th:inline="javascript"을 쓰면 문자열은 자동으로 " "를 붙여서 script단에서 동작한다. 숫자는 그냥 나온다. ( th:inline="javascript"에서 [[]] 사용시 한글은 퍼센트 인코딩이 되어서 나오니까, 주의할 것! )
    • th:inline="javascript"을 사용하고 [[ ]], [( )]을 가지고 적절하게 맞게 사용해야 한다.
      • [( )] 형태로 꺼내쓰면 인코딩 없이 데이터가 나온다. [[ ]] 로 꺼내쓰면 인코딩 되어 나온다.
      • [( )] 형태로 쓰려거든 ' '를 직접 붙여줘야 한다. 
<div id="label1"></div>
<div id="label2"></div>
	
	
<script>
	let name1 = '[[${name}]]';
	let num1 = [[${num}]];
	let names1 = '[[${names}]]';
	let dto1 = '[[${dto}]]';
	// 소스 보기에서 자바스크립트 배열이 아니다. 
	document.getElementById('label1').textContent = name1;	
</script>

<script th:inline="javascript">
    //let name2 = '[[${name}]]'; // 이거 쓰면 " " 붙어서 나온다.
    let name2 = [[${name}]]; // 이거 쓰면 " " 붙어서 나온다.
    let num2 = [[${num}]];
    let names2 = [[${names}]];
    let dto2 = [[${dto}]];
    let dto3 = '[(${dto})]'; // ' '를 안쓰면 문자열화가 안되어서 에러난다. 
    // 소스 보기에서 자바스크립트 배열이다. 손댈것이 없다.  
    document.getElementById('label2').textContent = name2;
</script>

 

결과

 

+ Recent posts