需要一个轻量级C++模板引擎

In need of a lightweight C++ Template Engine

本文关键字:C++ 轻量级 引擎 一个      更新时间:2023-10-16

我需要一个非常轻量级、快速、C++的模板引擎。我一直在测试 CTemplate,它符合我的需求,但它有点慢。我已经查看了本网站上推荐的许多其他模板引擎,但其中大多数都比 CTemplate 更复杂,我正在寻找相反的情况。我真正需要的是简单的文本替换,但更愿意使用现有的引擎。我还需要一个宽松的许可证,最好是MIT或BSD。

编辑:已调查以下内容:透明银,腾模板器,CTPP(这对我来说有点复杂...我对C++和 linux 开发环境很陌生)QC模板,以及更多,只需要尝试记住它们

创建了一个,因为我也不喜欢将 boost 作为依赖项:-)

https://github.com/hughperkins/Jinja2CppLight

  • 使用 Jinja2 语法
  • 支持变量替换和 for 循环
  • 可以嵌套 for 循环:-)
  • 零依赖,只有C ++和标准库:-)

你可以试试syslandscape-tmpl。

项目为C++提供灵活而强大的模板引擎。

树状数据结构用于存储模板变量。变量可以是 int、字符串、列表或对象。

特征

  • 变量
  • 对于循环和嵌套的 for 循环
  • if
  • 和嵌套的 if
  • 包括其他模板

要求

C++11

模板存储

目前,该引擎仅支持模板的stringfile存储。

#include <iostream>
#include <memory>
#include <syslandscape/tmpl/data.h>
#include <syslandscape/tmpl/engine.h>
#include <syslandscape/tmpl/string_storage.h>
using syslandscape::tmpl::data;
using syslandscape::tmpl::engine;
using syslandscape::tmpl::storage;
using syslandscape::tmpl::string_storage;
int main()
{
  std::shared_ptr<string_storage> storage = std::make_shared<string_storage>();
  storage->put_template("/greetings.html", "Hello, I'm {$person.name}.");
  storage->put_template("/city.html", "I'm from {$person.city}.");
  storage->put_template("/age.html", "I'm {$person.age} years old.");
  storage->put_template("/examples.html", "n{$message}: "
                        "{% for item in data %}{$item}{%endfor%}");
  storage->put_template("/index.html",
                        "{%include /greetings.html%} "
                        "{%include /city.html%} "
                        "{%include /age.html%} "
                        "{%include /examples.html%}");
  engine e;
  e.set_storage(storage);
  data model;
  model["person"]["name"] = "Alex";
  model["person"]["city"] = "Montana";
  model["person"]["age"] = 3;
  model["message"] = "List example";
  model["data"].append("Answer is");
  model["data"].append(" 42");

  std::cout << e.process("/index.html", model) << std::endl;
  return 0;
}