> ## Content Index
> Fetch the complete content index at: https://www.popit.kr/llms.txt
> Use this file to discover other available public pages before exploring further.

# Thymeleaf에서 newline characters를 br tag로 교체
- URL: https://www.popit.kr/thymeleaf-replace-newline-br-tag/
- Published: 2016-11-13T05:25:56.000Z
- Updated: 2016-11-13T16:36:16.000Z
- Author: 김형준
- Tags: #소프트웨어, Thymeleaf, newline

이전에 자바로 웹 화면 개발할 때에는 무조건 jsp를 이용했는데 최근 Spring boot 을 살펴보고 있는데 여기는 Thymeleaf 를 기본 뷰 렌더링 엔진으로 사용한다길래 무턱대고 보고 있습니다.또 다른 문법을 익혀야 하는 것 빼고는 나름 나쁘지는 않은데 textarea에 입력된 내용에서 newline을 br로 바꿔주는 방법이 애매해서 관련 글을 찾아본 내용을 정리해봤습니다. 자세한 내용은 다음 글 참고하세요.

- [https://codedump.io/share/31NxwQq2tfIq/1/thymeleaf-replace-newline-characters-with-ltbrgt](https://codedump.io/share/31NxwQq2tfIq/1/thymeleaf-replace-newline-characters-with-ltbrgt?ref=popit.kr)

일반적으로는 다음과 같이 new line 문자를 br tag로 치환합니다.

> String text = "this is test\\nsecond line";  
> String textHtml = text.replace("\\n", "<br/>");

구글링해서 나온 여러 문서에는 Thymeleaf에서는 다음과 같이 사용하라고 합니다.

> ${#strings.replace(text, '\\n', '<br />')}

위와 같이 수정을 해도 동작하지 않는데 위 표현에는 두가지 문제가 있다고 합니다.

- Thymeleaf는 '\\n' 특수한 한 문자로 인식하지 않고 '\\', '\\n' 두개의 문자로 인식합니다.
- Thymeleaf의 parser는 표현식 내에 '<', '>' 를 허용하지 않기 때문에 '<br/'> 은 Exception을 발생시킵니다.

## 해결방법

이런 두가지 문제 때문에 위와 같이 직접적으로 사용할 수 없습니다. 첫번째 문제인 '\\n'을 해결하기 위해서는 Thymeleaf expression에서 직접 '\\n' 을 사용하지 않는 방법을 사용합니다. 두번째 문제인 '<' tag 문제는 &lt; &gt;를 사용하는 것입니다.

- 첫번째 방법: 모델에 attribute로 설정  
//controller  
model.addAttribute("newLineChar", '\\n');  
//view  
${#strings.replace(text, newLineChar, '&lt;br /&gt;')}
- 두번째 방법: System의 line.separator 환경 변수를 이용하는 방법  
${#strings.replace(text, T(System).getProperty('line.separator'), '&lt;br /&gt;')}
- 세번째 방법: Static 상수를 이용하는 방법 (별도로 정의해도 되지만 apache common의 상수 이용)  
${#strings.replace(desc, T(org.apache.commons.lang3.StringUtils).LF, '&lt;br /&gt;')}

저는 세번째 방법을 사용하였습니다.