diff --git a/README.md b/README.md index 01b11ba..0527d4c 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,10 @@ render("{{ round(3.1415, 3) }}", data); // 3.142 render("{{ odd(42) }}", data); // false render("{{ even(42) }}", data); // true render("{{ divisibleBy(42, 7) }}", data); // true + +// Set default values if variables are not defined +render("Hello {{ default(neighbour, "my friend") }}!") // "Hello Peter!" +render("Hello {{ default(colleague, "my friend") }}!") // "Hello my friend!" ``` ### Callbacks diff --git a/src/inja.hpp b/src/inja.hpp index 047129c..025f6a7 100644 --- a/src/inja.hpp +++ b/src/inja.hpp @@ -250,6 +250,7 @@ struct Parsed { Odd, Even, ReadJson, + Default, Callback }; @@ -443,6 +444,13 @@ public: if (result.is_null()) { throw std::runtime_error("Did not found json element: " + element.command); } return result; } + case Parsed::Function::Default: { + try { + return eval_expression(element.args[0], data); + } catch (std::exception e) { + return eval_expression(element.args[1], data); + } + } case Parsed::Function::Callback: { return map_callbacks[element.command](element.args, data); } @@ -575,7 +583,8 @@ public: {Parsed::Function::DivisibleBy, function_regex("divisibleBy", 2)}, {Parsed::Function::Odd, function_regex("odd", 1)}, {Parsed::Function::Even, function_regex("even", 1)}, - {Parsed::Function::ReadJson, Regex{"\\s*([^\\(\\)]*\\S)\\s*"}} + {Parsed::Function::ReadJson, Regex{"\\s*([^\\(\\)]*\\S)\\s*"}}, + {Parsed::Function::Default, function_regex("default", 2)} }; std::map regex_map_callbacks; diff --git a/test/src/unit-renderer.cpp b/test/src/unit-renderer.cpp index 1316f1f..d8d483f 100644 --- a/test/src/unit-renderer.cpp +++ b/test/src/unit-renderer.cpp @@ -133,6 +133,15 @@ TEST_CASE("functions") { CHECK( env.render("{{ even(12) }}", data) == "true" ); // CHECK_THROWS_WITH( env.render("{{ even(name) }}", data), "[json.exception.type_error.302] type must be number, but is string" ); } + + SECTION("default") { + CHECK( env.render("{{ default(11, 0) }}", data) == "11" ); + CHECK( env.render("{{ default(nothing, 0) }}", data) == "0" ); + CHECK( env.render("{{ default(name, \"nobody\") }}", data) == "Peter" ); + CHECK( env.render("{{ default(surname, \"nobody\") }}", data) == "nobody" ); + + CHECK_THROWS_WITH( env.render("{{ default(surname, lastname) }}", data), "Did not found json element: lastname" ); + } } TEST_CASE("callbacks") {