C, C++2009. 7. 8. 16:57


 

http://code.google.com/p/google-ctemplate/

Google
ctemplate c++ 기반의 템플릿 언어(?)이다. 물론 언어의 정의는 여러가지 이므로, 언어가
아니라고 볼 수도 있기는 하다(?). 이것의 사용 방법은 다음과 축약된다
 1) template
에 해당하는 file template element를 정의한다
.
 2) dictionary
 정의하고, dictionary element value를 설정한다

 3) ctemplate
을 사용하는 c++ 코드에 template element와 연결된 dictionary 값들을 입력한다
.
 4)
최종 generation 결과를 출력한다
.
    (
예제는 console 출력이지만, file로 적는 등의 방식도 가능할 것이다
.)  
홈페이지에서 공개한 다음 예제를 보자
.

Hello
{{NAME}},
You have just won ${{VALUE}}!
{{#IN_CA}}Well, ${{TAXED_VALUE}}, after taxes.{{/IN_CA}}

위의 내용은 example.tpl 이라는 template 파일이다.
{{
로 시작하고 }}로 종료하는 정규식 비슷한 형태의 tag template element 이다
.
{{#
로 시작하고 {{/로 종료하는 것은  template section이다
.
, 위에는 NAME, VALUE, TAXED_VALUE template element가 있고
,
IN_CA
라는 template section이 존재함을 알 수 있다
..
, 이제 이것을 처리하는 c++ 코드를 보자
.
예제는 0.95 버전에서는 namespace가 바뀌었으므로, 약간 수정하였다.

#include <stdlib.h>
#include <string>
#include <iostream>  
#include <ctemplate/template.h> // ctemplate header files
  

int main(int argc, char** argv) {

// dictionary를 만든다. dict.는 후에 template과 연결한다.

ctemplate::TemplateDictionary dict("example");

// dictionary에 값을 설정한다. 간단히 보자면, 일종의 map이다.

// NAME이라는 dictionary element값은 물론 dic안에서 중복되지 않는 고유 key이다.

dict.SetValue(  "NAME", "John Smith"  );

// 정수값으로 dictionary element value를 설정한다.

int winnings = rand() % 100000;
  dict
.SetIntValue( "VALUE", winnings );
 

// printf() format 식의 구조도 가능하다.
  dict
.SetFormattedValue( "TAXED_VALUE", "%.2f", winnings * 0.83 );
 
  // 아래는 section처리에 대한 부분이다.

// 해당 이름의 section이 존재하면 그 section을 표시한다.
 
if (1) { // if 문은 아래 코드를 실행하거나, 실행하지 않을 경우의 테스트를 위하여 넣어 두었다.
    dict
.ShowSection( "IN_CA" );
 
}

  //
, 이제 template을 템플릿 파일(example.tpl)에서 읽어 들이자.
  ctemplate
::Template* tpl
   
= ctemplate::Template::GetTemplate( "example.tpl", ctemplate::DO_NOT_STRIP );

                                                     
  std
::string output;

// dictionary template을 연결한다.
  tpl
->Expand( &output, &dict  );
 
  std
::cout << output; // 표준출력으로 값을 본다.

 
return 0;
}


이제 결과가 어떤지 예측해 보자.

웹프로그래밍을 해보신 분이라면, jsp, php 등이 정해진 이름이 있는 tag를 자료값과 치환하는

처리를 알고 있을 것이다. 위의 처리도 그와 비슷하다. ,

1)     NAME=John Smith

2)     VALUE=어떤 난수값(, 정수)

3)     TAXED_VALUE=VALUE 0.83 곱한값

4)     IN_CA 섹션은 보여 주어라.

라는 정보 설정이 된다.

 
[최종 결과]


Hello, John Smith

You have just won $100

Well, $83.00, after taxes.

 

반응형
Posted by Jay Two