Templtext 是一个小型的 C++ 文本模板处理库。它支持类似 bash 的变量(%VAR 或 %{VAR})。但主要特点是支持用户定义函数。该库是我创建的。
- 模板解析
- 变量替换
- 模板中的用户定义函数
- C++11
- GPL 许可
需要BOOST regex库,但下个版本会替换为std::regex
示例 1:
using namespace templtext;
Templ * t = new Templ( "Dear %SALUTATION %NAME. I would like to invite you for %TEXT. Sincerely yours, %MYNAME." );
std::map<std::string, std::string> tokens01 =
{
{ "SALUTATION", "Mr." },
{ "NAME", "John Doe" },
{ "TEXT", "an interview" },
{ "MYNAME", "Ty Coon" }
};
std::map<std::string, std::string> tokens02 =
{
{ "SALUTATION", "Sweetheart" },
{ "NAME", "Mary" },
{ "TEXT", "a cup of coffee" },
{ "MYNAME", "Bob" }
};
std::cout << t->format( tokens01 ) << std::endl;
std::cout << t->format( tokens02 ) << std::endl;
输出:
Dear Mr. John Doe. I would like to invite you for an interview. Sincerely yours, Ty Coon.
Dear Sweetheart Mary. I would like to invite you for a cup of coffee. Sincerely yours, Bob.
示例 2:
using namespace templtext;
std::unique_ptr<Templ> tf1( new Templ( "You have got an $decode( 1 )." ) );
std::unique_ptr<Templ> tf2( new Templ( "You have got an $decode( 2 )." ) );
std::unique_ptr<Templ> tf3( new Templ( "English version - $decode_loc( 1, EN )." ) );
std::unique_ptr<Templ> tf4( new Templ( "German version - $decode_loc( 1, DE )." ) );
std::unique_ptr<Templ> tf5( new Templ( "Flexible version - $decode_loc( 1, %LANG )." ) );
tf1->set_func_proc( func );
tf2->set_func_proc( func );
tf3->set_func_proc( func );
tf4->set_func_proc( func );
tf5->set_func_proc( func );
Templ::MapKeyValue map1 =
{
{ "LANG", "EN" }
};
Templ::MapKeyValue map2 =
{
{ "LANG", "DE" }
};
std::cout << tf1->format() << std::endl;
std::cout << tf2->format() << std::endl;
std::cout << tf3->format() << std::endl;
std::cout << tf4->format() << std::endl;
std::cout << tf5->format( map1 ) << std::endl;
std::cout << tf5->format( map2 ) << std::endl;
输出:
You have got an apple.
You have got an orange.
English version - apple.
German version - Apfel.
Flexible version - apple.
Flexible version - Apfel.