Skip to content

Commit 8e4a9ba

Browse files
author
ochafik
committed
minja: allow none input to selectattr, and add safe passthrough filter
1 parent 5f5be9c commit 8e4a9ba

File tree

2 files changed

+7
-0
lines changed

2 files changed

+7
-0
lines changed

common/minja.hpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2329,6 +2329,9 @@ inline std::shared_ptr<Context> Context::builtins() {
23292329
auto & items = args.at("items");
23302330
return (int64_t) items.size();
23312331
}));
2332+
globals.set("safe", simple_function("safe", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
2333+
return args.at("value");
2334+
}));
23322335
globals.set("list", simple_function("list", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
23332336
auto & items = args.at("items");
23342337
if (!items.is_array()) throw std::runtime_error("object is not iterable");
@@ -2415,6 +2418,8 @@ inline std::shared_ptr<Context> Context::builtins() {
24152418
globals.set("selectattr", Value::callable([=](const std::shared_ptr<Context> & context, Value::Arguments & args) {
24162419
args.expectArgs("selectattr", {2, std::numeric_limits<size_t>::max()}, {0, 0});
24172420
auto & items = args.args[0];
2421+
if (items.is_null())
2422+
return Value::array();
24182423
auto attr_name = args.args[1].get<std::string>();
24192424

24202425
bool has_test = false;

tests/test-minja.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,9 @@ static void test_error_contains(const std::string & template_str, const json & b
149149
}
150150

151151
static void test_template_features() {
152+
test_render(R"({{ 1 | safe }})", {}, {}, "1");
152153
test_render(R"({{ 'abc'.endswith('bc') }},{{ ''.endswith('a') }})", {}, {}, "True,False");
154+
test_render(R"({{ none | selectattr("foo", "equalto", "bar") | list }})", {}, {}, "[]");
153155
test_render(R"({{ 'a' in {"a": 1} }},{{ 'a' in {} }})", {}, {}, "True,False");
154156
test_render(R"({{ 'a' in ["a"] }},{{ 'a' in [] }})", {}, {}, "True,False");
155157
test_render(R"({{ [{"a": 1}, {"a": 2}, {}] | selectattr("a", "equalto", 1) }})", {}, {}, R"([{'a': 1}])");

0 commit comments

Comments
 (0)