Logo Pico-Framework A web-first embedded framework for C++
Loading...
Searching...
No Matches
HtmlTemplateView.cpp
Go to the documentation of this file.
1
9
10HtmlTemplateView::HtmlTemplateView(const std::string &source, TemplateSource mode)
11 : mode_(mode)
12{
14 {
15 templateSource_ = source;
16 }
17 else
18 {
19 filePath_ = source;
20 }
21}
22
23std::string HtmlTemplateView::render(const std::map<std::string, std::string> &context) const
24{
25 std::string tpl;
26
28 {
29 tpl = templateSource_;
30 }
31 else
32 {
33 auto *storage = AppContext::get<StorageManager>();
34 std::vector<uint8_t> buf;
35 if (storage && storage->readFile(filePath_, buf))
36 {
37 tpl.assign(buf.begin(), buf.end());
38 }
39 else
40 {
41 tpl = "<h1>Template not found</h1>";
42 }
43 }
44
45 for (const auto &[key, value] : context)
46 {
47 std::string placeholder = "{{" + key + "}}";
48 size_t pos = 0;
49 while ((pos = tpl.find(placeholder, pos)) != std::string::npos)
50 {
51 tpl.replace(pos, placeholder.length(), value);
52 pos += value.length();
53 }
54 }
55
56 return tpl;
57}
58
60{
61 return "text/html";
62}
HTML template rendering view, supporting both inline and file-based templates.
TemplateSource
Abstract interface for file and directory storage backends.
static constexpr std::uintptr_t getTypeKey()
Definition AppContext.h:91
std::string getContentType() const override
Return the MIME content type for this view.
HtmlTemplateView(const std::string &source, TemplateSource mode=TemplateSource::Inline)
TemplateSource mode_
std::string filePath_
std::string templateSource_
std::string render(const std::map< std::string, std::string > &context={}) const override
Render the view body.