Skip to content

Commit

Permalink
at function for objects
Browse files Browse the repository at this point in the history
  • Loading branch information
pantor committed Jun 9, 2021
1 parent b473873 commit 4e90947
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 5 additions & 1 deletion include/inja/renderer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>()));
if (args[0]->is_object()) {
json_eval_stack.push(&args[0]->at(args[1]->get<std::string>()));
} else {
json_eval_stack.push(&args[0]->at(args[1]->get<int>()));
}
} break;
case Op::Default: {
const auto test_arg = get_arguments<1, 0, false>(node)[0];
Expand Down
2 changes: 2 additions & 0 deletions test/test-functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

Expand Down

0 comments on commit 4e90947

Please sign in to comment.