From 4e909475ea1c386d54c174d49f0b27d2d9008962 Mon Sep 17 00:00:00 2001 From: pantor Date: Wed, 9 Jun 2021 22:26:07 +0200 Subject: [PATCH] at function for objects --- README.md | 3 +++ include/inja/renderer.hpp | 6 +++++- test/test-functions.cpp | 2 ++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3359e8f..92e45ad 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,9 @@ render("{{ float(\"1.8\") > 2 }}", data); // false render("Hello {{ default(neighbour, \"my friend\") }}!", data); // "Hello Peter!" render("Hello {{ default(colleague, \"my friend\") }}!", data); // "Hello my friend!" +// Access an objects value dynamically +render("{{ at(time, \"start\") }} to {{ time.end }}", data); // "16 to 22" + // Check if a key exists in an object render("{{ exists(\"guests\") }}", data); // "true" render("{{ exists(\"city\") }}", data); // "false" diff --git a/include/inja/renderer.hpp b/include/inja/renderer.hpp index af774b2..d33cb46 100644 --- a/include/inja/renderer.hpp +++ b/include/inja/renderer.hpp @@ -343,7 +343,11 @@ class Renderer : public NodeVisitor { } break; case Op::At: { const auto args = get_arguments<2>(node); - json_eval_stack.push(&args[0]->at(args[1]->get())); + if (args[0]->is_object()) { + json_eval_stack.push(&args[0]->at(args[1]->get())); + } else { + json_eval_stack.push(&args[0]->at(args[1]->get())); + } } break; case Op::Default: { const auto test_arg = get_arguments<1, 0, false>(node)[0]; diff --git a/test/test-functions.cpp b/test/test-functions.cpp index 0ddcbf0..e920ff2 100644 --- a/test/test-functions.cpp +++ b/test/test-functions.cpp @@ -70,6 +70,8 @@ TEST_CASE("functions") { SUBCASE("at") { CHECK(env.render("{{ at(names, 0) }}", data) == "Jeff"); CHECK(env.render("{{ at(names, i) }}", data) == "Seb"); + CHECK(env.render("{{ at(brother, \"name\") }}", data) == "Chris"); + CHECK(env.render("{{ at(at(brother, \"daughters\"), 0) }}", data) == "Maria"); // CHECK(env.render("{{ at(names, 45) }}", data) == "Jeff"); }