Skip to content

Commit b0b564a

Browse files
committed
Fully implement recursive loops
1 parent b2b7b2d commit b0b564a

File tree

2 files changed

+15
-18
lines changed

2 files changed

+15
-18
lines changed

src/statements.cpp

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
#include "template_impl.h"
44
#include "value_visitors.h"
55

6+
#include <iostream>
7+
68

79
namespace jinja2
810
{
@@ -17,7 +19,7 @@ void ForStatement::Render(OutStream& os, RenderContext& values)
1719
void ForStatement::RenderLoop(const InternalValue& loopVal, OutStream& os, RenderContext& values)
1820
{
1921
auto& context = values.EnterScope();
20-
22+
2123
InternalValueMap loopVar;
2224
context["loop"] = MapAdapter::CreateAdapter(&loopVar);
2325
if (m_isRecursive)
@@ -26,21 +28,27 @@ void ForStatement::RenderLoop(const InternalValue& loopVal, OutStream& os, Rende
2628
bool isSucceeded = false;
2729
auto parsedParams = helpers::ParseCallParams({{"var", true}}, params, isSucceeded);
2830
if (!isSucceeded)
31+
{
2932
return;
33+
}
3034

3135
auto var = parsedParams["var"];
3236
if (!var)
37+
{
3338
return;
39+
}
3440

3541
RenderLoop(var->Evaluate(context), stream, context);
36-
});
37-
42+
});
3843
}
3944

4045
bool isConverted = false;
4146
auto loopItems = ConvertToList(loopVal, InternalValue(), isConverted);
4247
if (!isConverted)
43-
return;
48+
{
49+
values.ExitScope();
50+
return;
51+
}
4452

4553
if (m_ifExpr)
4654
{

test/forloop_test.cpp

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ b[1] = image[1];
337337
}
338338

339339

340-
TEST(ForLoopTest, DISABLED_RecursiveLoop)
340+
TEST(ForLoopTest, RecursiveLoop)
341341
{
342342
std::string source = R"(
343343
{%set items=[
@@ -357,9 +357,7 @@ TEST(ForLoopTest, DISABLED_RecursiveLoop)
357357
{'name'='child3_3'}
358358
]}
359359
] %}
360-
{% for i in items recursive %}
361-
{{i.name}} -> {{loop(i.children)}}
362-
{% endfor %}
360+
{% for i in items recursive %}{{i.name}} -> {{loop(i.children)}}{% endfor %}
363361
)";
364362

365363
Template tpl;
@@ -370,16 +368,7 @@ TEST(ForLoopTest, DISABLED_RecursiveLoop)
370368
std::string result = tpl.RenderAsString(params);
371369
std::cout << "[" << result << "]" << std::endl;
372370
std::string expectedResult = R"DELIM(
373-
a[0] = image[0];
374-
b[0] = image[0];
375-
b[1] = image[1];
376-
a[1] = image[1];
377-
b[0] = image[0];
378-
b[1] = image[1];
379-
a[2] = image[2];
380-
b[0] = image[0];
381-
b[1] = image[1];
382-
)DELIM";
371+
root1 -> child1_1 -> child1_2 -> child1_3 -> root2 -> child2_1 -> child2_2 -> child2_3 -> root3 -> child3_1 -> child3_2 -> child3_3 -> )DELIM";
383372

384373
EXPECT_EQ(expectedResult, result);
385374
}

0 commit comments

Comments
 (0)