Refactored template loading to its own class for performance
[biaweb2.git] / biawebdoclist.hpp
1 #ifndef __BIAWEBDOCITEMLIST__
2 #define __BIAWEBDOCITEMLIST__
3 #include <ctime>
4 #include <string>
5 #include <fstream>
6 #include <iostream>
7 #include <iomanip>
8 #include <list>
9 #include <fmt/format.h>
10 #include <fmt/chrono.h>
11 #include "biawebstrings.hpp"
12 #include "biawebdocument.hpp"
13 #include "biawebtemplate.hpp"
14
15 // to implement a list of items (documents) with creation/modified date/time display
16 namespace biaweb {
17 // to implement a single document item
18 class DocListItem {
19 protected:
20 // Just the required fields to build the item
21 std::string title;
22 std::string url;
23 std::time_t ctime;
24 std::time_t mtime;
25 public:
26 DocListItem (std::string title, std::string url,
27 std::time_t ctime, std::time_t mtime ) {
28 this->title = escape_html (title);
29 this->url = url;
30 this->ctime = ctime;
31 this->mtime = mtime;
32 }
33
34 std::time_t get_mtime() {
35 return this->mtime;
36 }
37 void set_mtime(std::time_t mtime) {
38 this->mtime = mtime;
39 }
40 std::time_t get_ctime() {
41 return this->ctime;
42 }
43 void set_ctime(std::time_t ctime) {
44 this->ctime = ctime;
45 }
46
47 std::string get_url() {
48 return this->url;
49 }
50
51 void set_url(std::string url) {
52 this->url = url;
53 }
54
55 std::string get_title() {
56 return this->title;
57 }
58 void set_title(std::string title) {
59 this->title = escape_html (title);
60 }
61
62 // output to HTML vide the template
63 std::string to_html (Template *t);
64 };
65
66 // output to HTML vide the template
67 std::string DocListItem::to_html (Template *t) {
68 std::string templstr = t->get_doclistitem_tpl ();
69 std::tm c, m;
70 c = *std::localtime (&this->ctime);
71 m = *std::localtime (&this->mtime);
72
73 std::string outputhtml = fmt::format (templstr, fmt::arg("url", this->url),
74 fmt::arg("doctitle", this->title),
75 fmt::arg("cdate", c),
76 fmt::arg("mdate", m));
77
78 return outputhtml;
79 }
80
81 // to implement a document list (or table)
82 class DocList {
83 protected:
84 std::string title;
85 std::list<DocListItem> items;
86 public:
87 void set_title (std::string title) {
88 this->title = escape_html (title);
89 }
90 // add a document item
91 void add_document_item (DocListItem docitem) {
92 this->items.insert (this->items.cend(), docitem);
93 }
94 // render to HTML from a template
95 std::string to_html (Template *t);
96 };
97
98 std::string DocList::to_html (Template *t) {
99 std::string templstr = t->get_doclist_tpl ();
100
101 std::string outputhtml = "";
102 // if the number of elements is non zero
103 if (this->items.size () != 0) {
104 std::string docitems = "";
105 for (DocListItem item : this->items)
106 docitems += item.to_html (t);
107
108 outputhtml = fmt::format (templstr,
109 fmt::arg ("title", this->title),
110 fmt::arg ("docitems", docitems));
111 }
112 return outputhtml;
113 }
114 }
115
116 #endif