블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

BroadleafThymeleaf이라는 서버 템플릿 엔진을 사용하고 있다. Broadleaf은 Tymeleaf을 상속받아 확장한 <blc:XXX> 태그를 xxxProcessor 클래스에 정의하고 있다. 따라서 템플릿에는 Tymeleaf 태그와 Broadleaf이 정의한 <blc:XXX> 태그가 함께 사용된다. 이에 대해 간략히 알아보고 Twitter Bootstrap을 템플릿에 적용해 보자 




Broadleaf에서 Thymeleaf 역할 


  - Thymeleaf은 레이아웃 템플릿 보다 텍스트 템플릿에 가깝고 객체값을 받아서 화면에 표현해 주는 제어구문들을 가지고 있다.

  - AngularJS의 Directive와 서버 템플릿의 Taglib로 사용자 정의한 태그와 백앤드/프론트앤드만 틀리고 유사하다고 하겠다. 

  - 그럼 데이터는 어떻게 주고 받아서 표현할까?

     + Thymeleaf은 HTML을 해석하고 맵핑된 객체를 통해 Value가 설정된 HTML을 최종 클라이언트에 전송한다. 

     + 이때 객체 정보는 Broadlead의 <blc:XXX> 태그에서 Broadleaf core소스에서 정의한 XXXProcessor 가 YYYService를 통해서 Thymleaf에 사용할 객체를 조회/설정/전달한다. 


  - core/broadlleaf-framework : Hibernate와 연결된 DAO와 업무 도메인 Service가 존재한다. 

  - core/broadleaf-framework-web : web이므로 프론트단에 필요한 폼, 필터, 태그처리 프로세스(Processor)등이 존재한다. 

    + DemoSite의 메인 페이지 템플릿은 /site/src/main/webapp/WEB-INF/templates/layout/home.html 해당 파일이다. 

    + home.html을 열어보면 맨위에 하기와 같이 <head>가 설정되어 있다. 

    + <head> 태그를 core/broadleaf-framework-web의 org.broadleafcommerce.core.web.processor.HeadProcessor 가 처리한다.

    + HeadProcessor는 pageTitle 값을 처리하는 클래스이다. 

    + 즉, XxxYyyZzzProcessor 가 있고 태그로 <xxx-yyy-zzz> 태그를 사용하면 XxxYyyZzzProcessor 가 동작하는 것이다. 

// home.html 일부 내역


<head th:include="/layout/partials/head (pageTitle='Broadleaf Demo - Heat Clinic')"></head>

<body>

    <div id="notification_bar"></div>

    <header th:substituteby="layout/partials/header" />

    

    <div id="content" class="width_setter group" role="main">

        <nav th:substituteby="layout/partials/nav" />

        <blc:content contentType="Homepage Banner Ad" />       

        <div id="banners" th:if="${contentItem !=null and contentItem['targetUrl'] != null and contentItem['imageUrl'] != null}">

            <a th:href="@{${contentItem['targetUrl']}}"><img blc:src="@{${contentItem['imageUrl']}}" /></a>       

        </div>

  ... 중략 ...

</body>



// HeadProcessor.java 일부 내역


import org.thymeleaf.processor.element.AbstractFragmentHandlingElementProcessor;

public class HeadProcessor extends AbstractFragmentHandlingElementProcessor {

    @Resource(name = "blHeadProcessorExtensionManager")

    protected HeadProcessorExtensionListener extensionManager;

    public static final String FRAGMENT_ATTR_NAME = StandardFragmentAttrProcessor.ATTR_NAME;

    protected String HEAD_PARTIAL_PATH = "layout/partials/head";


    public HeadProcessor() {

        super("head");

    }


    @Override

    public int getPrecedence() {

        return 10000;

    }


    @Override

    protected boolean getRemoveHostNode(final Arguments arguments, final Element element) {

        return true;

    }


    @Override

    @SuppressWarnings("unchecked")

    protected List<Node> computeFragment(final Arguments arguments, final Element element) {

        String pageTitle = element.getAttributeValue("pageTitle");

        try {

            Expression expression = (Expression) StandardExpressions.getExpressionParser(arguments.getConfiguration())

                    .parseExpression(arguments.getConfiguration(), arguments, pageTitle);

            pageTitle = (String) expression.execute(arguments.getConfiguration(), arguments);

        } catch (TemplateProcessingException e) {}


        ((Map<String, Object>) arguments.getExpressionEvaluationRoot()).put("pageTitle", pageTitle);

      ((Map<String, Object>) arguments.getExpressionEvaluationRoot()).put("additionalCss", element.getAttributeValue("additionalCss"));


        extensionManager.processAttributeValues(arguments, element);

        return new ArrayList<Node>();

    }

}


  - <blc:content> 는 특별히 admin/broadleaf-conentmanagement-modul 에서 org.broadleafcommerce.cms.web.processor.ContentProcessor 로 존재한다.

  - <blc.content> 태그는 내부적으로 서비스를 호출해서 contentItem을 값을 설정해 준다. 이때 contentType="Homepage Banner Ad"는 admin 페이지에서 설정해주는 것이다. 즉, 관리 도구를 통해 Content Mangement를 할 수 있고 이를 간단히 <blc:xxx> 태그를 사용한다.

1) admin 프로젝트에서 ant task중 jetty-demo 실행

2) http://localhost:8081/admin (id:admin, password: admin)

3) Content 메뉴의 content items 목록이 나온다. 여기서 "Content Type"으로 찾으면 됨 



  - Thymeleaf의 특정 인터페이스를 상속받으면 자신만의 태그를 쉽게 만들수 있고 Broadleaf에서는 XXXProcessor로 만들고 있는 것이다. 그리고 <blc:xxx> 태그를 만들어 xxxProcessor내부에서 Service를 통해 Hibernate를 호출해 업무적인 부분을 처리하고 있다.


  얼핏 보면 AngularJS의 Directive를 만들고 내부에서 AngularJS 서비스를 DI(Dependency Injection) 받아 호출하고 서비스내에서 서버로 AJAX 호출하는 계층을 두는 것과 유사하다. 따라서 Broadleaf에서 정의한 xxxProcessor들을 AngularJS Directive로 전환하면 AngularJS기반의 SPA(Single Page Application)으로의 전환이 가능하다. 




Twitter Bootstrap 적용하기 


  - 트위터 부트스트랩은 UI Framework으로 RWD (Responsible Web Design)을 적용할 수 있는 CSS를 제공하고 많이 사용하는 jQuery 플러그인도 함께 제공된다. 

  - 우선 트위터 부트스트랩 v3.3.1을 다운로드하고 압축을 풀면 css, fonts, js 폴더가 있다 

  - site/src/main/webapp 밑에 css, fonts, js를 복사한다. 

  - site/src/main/webapp/WEB-INF/templates/layout 폴더가 상/하/메인에 대한 레이아웃을 설정하는 템플릿 HTML이 존재한다

  - 상단 head.html에 bootstrap.css를 추가하고 하단 footer.html에 bootstrap.js를 하기와 같이 추가한다 

// layout/partials/head.html 


    <blc:bundle name="style.css" 

                mapping-prefix="/css/"

                files="bootstrap.css,

                       style.css,

                       jquery.rating.css" />



// layout/partials/footer.html


    <blc:bundle name="lib.js" 

                mapping-prefix="/js/"

                files="plugins.js,

                       libs/jquery.MetaData.js,

                       libs/jquery.rating.pack.js,

                       libs/jquery.dotdotdot-1.5.1.js,

                       bootstrap.js" />


  - 기존의 CSS는 전부 무시하고 트위터 부트스트랩을 재적용하는 단계이다. 따라서 DemoSite에 적용한 css/style.css 의 내용을 전부 제거 한다.

  - 제거한 내용에 몇가지 CSS를 하기와 같이 적용한다.

/************************************/

/* Header Customizing               */

/************************************/

.navbar .navbar-top {

height: 30px;

padding-top: 5px;

background-color: #F5F5F5;

transition: all 0.1s ease-out 0s;

-webkit-transition: all 0.1s ease-out 0s;

-moz-transition: all 0.1s ease-out 0s;

-ms-transition: all 0.1s ease-out 0s;

-o-transition: all 0.1s ease-out 0s;

font-size: 11px;

line-height: 11px;

text-transform: uppercase;

}


.navbar .container-fluid {

background-color:#525252;

}


.navbar-inverse .navbar-nav > li > a, .navbar-inverse .navbar-brand {

color: #FEFEFE;

}


html, body {

height: 100%;

}


  - site의 WEB-INF/templates/layout/home.html 의 내역에서 필요없는 부분을 주석처리 하고 partials/nav.html 를 사용한다. 

    + <blc:xxx> 로 사용하는 부분을 전부 제거했다. 나중에 필요한 부분에 넣을 것이다. 

    + partails/nav.html 에서 메뉴역할을 하도록 partails/header.html을 nav.html에 통합할 것이다. 

    + <blc:form> 을 통해 제품 검색을 수행한다. 

<head th:include="/layout/partials/head (pageTitle='Broadleaf And Twitter Bootstrap')"></head>


<body>

    <div id="notification_bar"></div>

    

    <nav th:substituteby="layout/partials/nav" />

    

    <footer th:substituteby="layout/partials/footer" />

    

</body>

</html>


  - 다음으로 메뉴를 nav.html에 적용한다. 

    + 트위터 부트스트랩에 맞게 RWD를 적용하고 카테고리(Categories)에 대해 Thymeleaf의 <li th:each> 구문을 적용한다.

    + Admin 화면 (http://localhost:8081/admin) 에서 Category에 해당하는 내용이 메뉴에 적용되는 것으로 broadleaf-framework-web 프로젝트의 org.broadleafcommerce.core.web.processor.CategoriesProcessor가 처리한다. 

<nav>   

    <div th:remove="all">

        <!--

             This template displays the navigation of the site by looking up the category named "Nav"

             and building a list of the categories sub-categories.                          

        -->

    </div>

    

    <blc:categories resultVar="navCategories" parentCategory="Primary Nav" maxResults="6" />

    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">

    

      <!-- TOP Header  -->

      <div class="navbar-top">

      <div class="container">

      <div class="pull-right">

   

    <div th:if="${customer.anonymous}"  th:remove="tag">

            <a th:href="@{/login}">

                <span th:text="#{home.login}">Login</span>

            </a>

            &nbsp;|&nbsp; 

            <a th:href="@{/register}">

                <span th:text="#{home.register}">Register</span>

            </a>

            &nbsp;|&nbsp; 

        </div>

        <div th:unless="${customer.anonymous}" th:remove="tag">

            <span><span th:text="#{home.welcome}">Welcome</span>, <a th:href="@{/account}" th:text="${customer.firstName}"></a></span>

            &nbsp;|&nbsp; 

            <a th:href="@{/logout}">

                <span th:text="#{home.logout}">Logout</span>

            </a>

            &nbsp;|&nbsp; 

        </div>

        <img blc:src="@{/img/icon-cart.jpg}" alt="Shopping Cart Icon" />&nbsp; 

        <a id="cartLink" th:href="@{/cart}">

            <span id="headerCartItemWordSingular_i18n" style="display: none;" th:text="#{home.item}" />

            <span id="headerCartItemWordPlural_i18n" style="display: none;" th:text="#{home.items}" />

            <span class="headerCartItemsCount" th:text="${cart.itemCount}" />

            <span class="headerCartItemsCountWord" th:text="${cart.itemCount == 1} ? #{home.item} :  #{home.items}" />

        </a>

   

    </div>   

    </div>

      </div>

      

      <!-- Responsible Menu -->

      <div class="container-fluid">

        <div class="navbar-header">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">

            <span class="sr-only">Toggle navigation</span>

            <span class="icon-bar"></span>

            <span class="icon-bar"></span>

            <span class="icon-bar"></span>

          </button>

          <a class="navbar-brand" href="/">eCommerce</a>

        </div>

        

        <div id="navbar" class="navbar-collapse collapse">

          <!-- Categories -->

          <ul class="nav navbar-nav navbar-right">

       

        <blc:form class="navbar-form navbar-right" style="margin-left:5px; margin-right:5px" th:action="@{/search}" method="GET">

            <input type="search" class="form-control" placeholder="SEARCH PROD" name="q" th:value="${originalQuery}" />

            <input type="submit" class="btn btn-default" value="go" />

    </blc:form>

   

            <li th:each="category : ${navCategories}" th:unless="${#strings.isEmpty(category.url)}">

            <a class="home" th:href="@{${category.url}}" th:class="${categoryStat.first}? 'home'" th:text="${category.name}"></a>

        </li>

          </ul>

        </div>

      </div>

      

    </nav>

    

</nav>


결과 화면은 다음과 같이 정상적인 화면과 RWD 메뉴가 적용된 화면이다. 



* 소스는 제공되지 않습니다. 관심있으신 분은 별도로 문의해 주세요. 



참조 


  - http://www.broadleafcommerce.org

  - Broadleaf core 깃헙 소스

  - http://www.thymeleaf.org

  - 트위터 부트스트랩

posted by 윤영식