Add exists() function that checks existence of key (#38)

* Add exists() function that checks existence of key

Adds an exists() function that checks whether a given key exists in the
data. If only one argument is provided to exists(), the global data is
queried for the item. If two arguments are given, the first argument
specifies the object to query for the key given as second argument.

Also adds corresponding unit tests and updates README for
documentation.

* Split exists() into exists() and existsIn()

Splits the exists() function, which previously took both one or two
arguments, into an exists() function accepting one and an existsIn()
function accepting two arguments.
This commit is contained in:
Samuel Leweke
2018-04-02 15:54:00 +02:00
committed by pantor
parent 138e0da339
commit 1cb6b15cca
4 changed files with 40 additions and 0 deletions

View File

@@ -104,6 +104,9 @@ TEST_CASE("functions") {
data["city"] = "New York";
data["names"] = {"Jeff", "Seb", "Peter", "Tom"};
data["temperature"] = 25.6789;
data["brother"]["name"] = "Chris";
data["brother"]["daughters"] = {"Maria", "Helen"};
data["property"] = "name";
SECTION("upper") {
CHECK( env.render("{{ upper(name) }}", data) == "PETER" );
@@ -203,6 +206,22 @@ TEST_CASE("functions") {
CHECK( env.render("{{ default(surname, \"nobody\") }}", data) == "nobody" );
CHECK_THROWS_WITH( env.render("{{ default(surname, lastname) }}", data), "[inja.exception.render_error] variable '/lastname' not found" );
}
SECTION("exists") {
CHECK( env.render("{{ exists(\"name\") }}", data) == "true" );
CHECK( env.render("{{ exists(\"zipcode\") }}", data) == "false" );
CHECK( env.render("{{ exists(name) }}", data) == "false" );
CHECK( env.render("{{ exists(property) }}", data) == "true" );
}
SECTION("existsIn") {
CHECK( env.render("{{ existsIn(brother, \"name\") }}", data) == "true" );
CHECK( env.render("{{ existsIn(brother, \"parents\") }}", data) == "false" );
CHECK( env.render("{{ existsIn(brother, property) }}", data) == "true" );
CHECK( env.render("{{ existsIn(brother, name) }}", data) == "false" );
CHECK_THROWS_WITH( env.render("{{ existsIn(sister, \"lastname\") }}", data), "[inja.exception.render_error] variable '/sister' not found" );
CHECK_THROWS_WITH( env.render("{{ existsIn(brother, sister) }}", data), "[inja.exception.render_error] variable '/sister' not found" );
}
}
TEST_CASE("callbacks") {