Skip to content

Commit

Permalink
Add dict.items
Browse files Browse the repository at this point in the history
  • Loading branch information
Pavel Belikov committed Dec 6, 2023
1 parent ede40f1 commit 14e29e9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/internal_value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ InternalValueList ListAdapter::ToValueList() const

InternalValue BuiltinMethod(InternalValue self, Callable::ExpressionCallable method)
{
auto result = InternalValue(RecursiveWrapper<Callable>(Callable(Callable::Kind::SpecialFunc, std::move(method))));
auto result = InternalValue(RecursiveWrapper<Callable>(Callable(Callable::Kind::UserCallable, std::move(method))));
result.SetParentData(std::move(self));
return result;
}
Expand Down Expand Up @@ -788,13 +788,30 @@ InternalValue DictUpdate(MapAdapter self)
);
}

InternalValue DictItems(MapAdapter self)
{
return BuiltinMethod(
self,
[self](const CallParams&, RenderContext&) {
InternalValueList items;
auto keys = self.GetKeys();
std::sort(keys.begin(), keys.end());
for (const auto& key : keys)
items.push_back(RecursiveWrapper<KeyValuePair>(KeyValuePair{key, self.GetValueByName(key)}));
return InternalValue(ListAdapter::CreateAdapter(std::move(items)));
}
);
}

InternalValue MapAdapter::GetBuiltinMethod(const std::string& name) const
{
if (!m_accessorProvider || !m_accessorProvider())
return InternalValue();

if (name == "update")
return DictUpdate(*this);
if (name == "items")
return DictItems(*this);

return InternalValue();
}
Expand Down
18 changes: 18 additions & 0 deletions test/statements_tets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,24 @@ R"(
R"(
a: 1
b: 2
)"
)
{
}

MULTISTR_TEST(ForTest, ForKeyValueInDictItems,
R"(
{% set d = {'a'=1,'b'=2} %}
{% for k, v in d.items() %}
{{ k }}: {{ v }}
{%- endfor %}
)",
//------------
R"(
a: 1
b: 2
)"
Expand Down

0 comments on commit 14e29e9

Please sign in to comment.