Add HTML autoescape (#292)

* add and document set_html_autoescape

* add render_to to Environment that accepts a string (and turns it into a Template)

* code style, update single include

* update ci

* revert macos-14 test

---------

Co-authored-by: pantor <lars.berscheid@online.de>
This commit is contained in:
bert hubertandpantor authored and GitHub committed 2024-10-05 09:08:46 +02:00
1 parent c360b19855
commit 807620c80c
6 files changed
+77 -9

No files matched your search

+1
View File
@@ -74,6 +74,7 @@ struct ParserConfig {
*/
struct RenderConfig {
bool throw_at_missing_includes {true};
bool html_autoescape {false};
};
} // namespace inja
+9
View File
@@ -93,6 +93,11 @@ public:
render_config.throw_at_missing_includes = will_throw;
}
/// Sets whether we'll automatically perform HTML escape
void set_html_autoescape(bool will_escape) {
render_config.html_autoescape = will_escape;
}
Template parse(std::string_view input) {
Parser parser(parser_config, lexer_config, template_storage, function_storage);
return parser.parse(input, input_path);
@@ -155,6 +160,10 @@ public:
return os;
}
std::ostream& render_to(std::ostream& os, const std::string_view input, const json& data) {
return render_to(os, parse(input), data);
}
std::string load_file(const std::string& filename) {
Parser parser(parser_config, lexer_config, template_storage, function_storage);
return Parser::load_file(input_path + filename);
+21 -1
View File
@@ -53,9 +53,29 @@ class Renderer : public NodeVisitor {
return !data->empty();
}
static std::string htmlescape(const std::string& data) {
std::string buffer;
buffer.reserve(1.1 * data.size());
for (size_t pos = 0; pos != data.size(); ++pos) {
switch (data[pos]) {
case '&': buffer.append("&amp;"); break;
case '\"': buffer.append("&quot;"); break;
case '\'': buffer.append("&apos;"); break;
case '<': buffer.append("&lt;"); break;
case '>': buffer.append("&gt;"); break;
default: buffer.append(&data[pos], 1); break;
}
}
return buffer;
}
void print_data(const std::shared_ptr<json> value) {
if (value->is_string()) {
*output_stream << value->get_ref<const json::string_t&>();
if (config.html_autoescape) {
*output_stream << htmlescape(value->get_ref<const json::string_t&>());
} else {
*output_stream << value->get_ref<const json::string_t&>();
}
} else if (value->is_number_unsigned()) {
*output_stream << value->get<const json::number_unsigned_t>();
} else if (value->is_number_integer()) {