forked from tindy2013/subconverter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate_jinja2.cpp
47 lines (43 loc) · 1.71 KB
/
template_jinja2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <string>
#include <jinja2cpp/user_callable.h>
#include <jinja2cpp/binding/nlohmann_json.h>
#include <jinja2cpp/template.h>
#include <nlohmann/json.hpp>
#include "interfaces.h"
#include "templates.h"
#include "webget.h"
#include "misc.h"
static inline void parse_json_pointer(nlohmann::json &json, const std::string &path, const std::string &value)
{
std::string pointer = "/" + replace_all_distinct(path, ".", "/");
json[nlohmann::json::json_pointer(pointer)] = value;
}
int render_template(const std::string &content, const template_args &vars, std::string &output, const std::string &include_scope)
{
jinja2::Template tpl;
nlohmann::json data;
for(auto &x : vars.global_vars)
parse_json_pointer(data["global"], x.first, x.second);
for(auto &x : vars.request_params)
parse_json_pointer(data["request"], x.first, x.second);
for(auto &x : vars.local_vars)
parse_json_pointer(data["local"], x.first, x.second);
tpl.Load(content);
jinja2::ValuesMap valmap = {{"global", jinja2::Reflect(data["global"])}, {"local", jinja2::Reflect(data["local"])}, {"request", jinja2::Reflect(data["request"])}};
valmap["fetch"] = jinja2::MakeCallable(jinja2_webGet, jinja2::ArgInfo{"url"});
valmap["replace"] = jinja2::MakeCallable([](const std::string &src, const std::string &target, const std::string &rep)
{
return regReplace(src, target, rep);
}, jinja2::ArgInfo{"src"}, jinja2::ArgInfo{"target"}, jinja2::ArgInfo{"rep"});
try
{
output = tpl.RenderAsString(valmap).value();
return 0;
}
catch (std::exception &e)
{
output = "Template render failed! Reason: " + std::string(e.what());
return -1;
}
return -2;
}