C++ string template library

后端 未结 10 1101
清酒与你
清酒与你 2020-12-16 01:23

I want simple C++ string based template library to replace strings at runtime.

For example, I will use

string template = \"My name is {{name}}\";
         


        
10条回答
  •  感情败类
    2020-12-16 02:02

    Update: The project has moved to Github and renamed into CTemplate: https://github.com/OlafvdSpek/ctemplate

    From the new project page:

    was originally called Google Templates, due to its origin as the template system used for Google search result pages. Now it has a more general name matching its community-owned nature.


    Have you tried Google's CTemplate library ? It seems to be exactly what you are looking for: http://code.google.com/p/google-ctemplate/

    Your example would be implemented like this:

    In example.tpl:

    My name is {{name}}

    In example.cc:

    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char** argv)
    {
      google::TemplateDictionary dict("example");
      dict.SetValue("name", "John Smith");
      google::Template* tpl = google::Template::GetTemplate("example.tpl",
                                                            google::DO_NOT_STRIP);
      std::string output;
      tpl->Expand(&output, &dict);
      std::cout << output;
      return 0;
    }
    

    Then:

    $ gcc example.cc -lctemplate -pthread
    
    $ ./a.out
    

    My name is John Smith

    Note that there is also a way to write templates as const strings if you don't want to bother writting your templates in separate files.

提交回复
热议问题