diff --git a/include/Parsodus/template.h b/include/Parsodus/template.h new file mode 100644 index 0000000..3ba1828 --- /dev/null +++ b/include/Parsodus/template.h @@ -0,0 +1,63 @@ +#pragma once +#ifndef PARSODUS_TEMPLATE_H +#define PARSODUS_TEMPLATE_H + +#include <map> +#include <string> +#include <vector> +#include <mstch/mstch.hpp> + +namespace pds { +namespace templ { + /** + * A changeable information structure for templates + */ + using TemplateContext = mstch::node; + + /** + * Make a TemplateContext string + */ + TemplateContext make_string(std::string); + + /** + * Make a TemplateContext map/dictionary + */ + TemplateContext make_map(std::map<const std::string, TemplateContext>); + + /** + * Make a TemplateContext array/vector + */ + TemplateContext make_array(std::vector<TemplateContext>); + + /** + * A generic wrapper around whichever templating system gets used + */ + class Template { + public: + /** + * Construct a Template from given filename + * + * @param filename The name of the file which contains the template rules + */ + Template(std::string filename); + + /** + * Destructor + */ + ~Template(); + + /** + * Render this template to `out` using the information in `context` + * + * @param out The ostream to render to + * @param context The information to provide the template rules while rendering + */ + void render(std::ostream& out, TemplateContext& context); + private: + std::string m_filename; + }; + +} //namespace templ +} //namespace pds + +#endif //PARSODUS_TEMPLATE_H diff --git a/src/template.cpp b/src/template.cpp new file mode 100644 index 0000000..50a1bc0 --- /dev/null +++ b/src/template.cpp @@ -0,0 +1,39 @@ +#include "Parsodus/template.h" +#include "mstch/mstch.hpp" + +#include <fstream> +#include <string> +#include <sstream> + +namespace pds { +namespace templ { + + TemplateContext make_string(std::string _string) { + return mstch::node(_string); + } + + TemplateContext make_map(std::map<const std::string, TemplateContext> _map) { + return mstch::map(_map); + } + + TemplateContext make_array(std::vector<TemplateContext> _array) { + return mstch::array(_array); + } + + + Template::Template(std::string filename) : m_filename(filename) + {} + + Template::~Template() + {} + + void Template::render(std::ostream& out, TemplateContext& context) { + std::ifstream file; + file.open (m_filename); + std::stringstream tmplt; + tmplt << file.rdbuf(); + file.close(); + out << mstch::render(tmplt.str(),context); + } +} +}