[SpringBoot] 스프링부트 프로젝트에 마크다운 적용하기 (타임리프 사용)

최가희·2022년 8월 8일
0

SpringBoot

목록 보기
11/13
post-thumbnail

마크다운 설치

build.gradle

...
dependencies {
    ...
    implementation 'org.commonmark:commonmark:0.18.2'
}
...



마크다운 컴포넌트 작성

CommonUtil.java
markdown 메서드는 마크다운 텍스트를 html 문서로 변환하여 리턴한다.

import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.stereotype.Component;

@Component
public class CommonUtil {
    public String markdown(String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }
}



템플릿에 마크다운 적용

question_detail.html

...
<!-- 질문 -->
<h2 class="border-bottom py-2" th:text="${question.subject}"></h2>
<div class="card my-3">
    <div class="card-body">
      	<!--마크다운 적용 부분 start-->
        <div class="card-text" th:utext="${@commonUtil.markdown(question.content)}"></div>
        <div class="d-flex justify-content-end">
         <!--마크다운 적용 부분 end-->
        ...

<!-- 답변 반복 시작 -->
<div class="card my-3" th:each="answer : ${question.answerList}">
    <a th:id="|answer_${answer.id}|"></a>
    <div class="card-body">
      	<!--마크다운 적용 부분 start-->
        <div class="card-text" th:utext="${@commonUtil.markdown(answer.content)}"></div>
        <div class="d-flex justify-content-end">
         <!--마크다운 적용 부분 end-->
        ...
  • 마크다운으로 변환된 HTML 문서를 제대로 표시하려면 escape 처리를 하지 않고 출력하는 th:utext를 사용해야 한다.
  • 만약 th:utext 대신 th:text를 사용할 경우 HTML의 태그들이 escape 처리되어 태그들이 그대로 화면에 보인다.



참고

점프 투 스프링

0개의 댓글