-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemplateengine.cpp
More file actions
98 lines (74 loc) · 2.1 KB
/
templateengine.cpp
File metadata and controls
98 lines (74 loc) · 2.1 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* Copyright (C) Alex Nekipelov (alex@nekipelov.net)
* License: BSD
*/
#include <map>
#include <fstream>
#include <boost/bind.hpp>
#include "templateengine.h"
#include "buildinhelpers.h"
namespace cpptl {
class TemplateEngineImpl {
public:
std::map<std::string, TemplateEngine::Helper> helpers;
std::map<std::string, Template> cache;
};
TemplateEngine::TemplateEngine()
{
pimpl.reset(new TemplateEngineImpl);
registerHelper("include", boost::bind(include, boost::ref(*this), _1, _2));
registerHelper("rawHtml", rawHtml);
}
TemplateEngine::~TemplateEngine()
{
}
Template TemplateEngine::templ(const std::string &text)
{
return Template(*this, text);
}
Template TemplateEngine::templFile(const std::string &fileName)
{
std::map<std::string, Template>::iterator it = pimpl->cache.find(fileName);
if( it != pimpl->cache.end() )
return it->second;
std::ifstream ifs(fileName.c_str());
if( ifs )
{
ifs.seekg(0, std::ios::end);
std::ifstream::pos_type fileSize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::string content;
content.resize(fileSize);
ifs.read(&content[0], fileSize);
Template templ(*this, content);
pimpl->cache.insert( std::make_pair(fileName, templ) );
return templ;
}
else
{
std::cerr << "Can`t open file" << fileName << std::endl;
}
return Template(*this, std::string());
}
bool TemplateEngine::hasHelper(const std::string &name)
{
return pimpl->helpers.find(name) != pimpl->helpers.end();
}
void TemplateEngine::registerHelper(const std::string &name, const Helper &handler)
{
pimpl->helpers[name] = handler;
}
Value TemplateEngine::callHelper(const std::string &name, const Value &context, const Value &args) const
{
std::map<std::string, TemplateEngine::Helper>::iterator it = pimpl->helpers.find(name);
if( it != pimpl->helpers.end() )
{
return it->second(context, args);
}
else
{
std::cerr << "helper \"" << name << "\" not found" << std::endl;
return std::string();
}
}
} // namespace cpptl