From bc020a5ee018c28b73502e3335a2da2e18fc3227 Mon Sep 17 00:00:00 2001 From: pantor Date: Sat, 27 Jun 2020 17:18:25 +0200 Subject: [PATCH] add count variables to template --- include/inja/template.hpp | 11 +++++++++++ single_include/inja/inja.hpp | 11 +++++++++++ test/unit-renderer.cpp | 11 +++++++++++ 3 files changed, 33 insertions(+) diff --git a/include/inja/template.hpp b/include/inja/template.hpp index 2db52d4..bc63be2 100644 --- a/include/inja/template.hpp +++ b/include/inja/template.hpp @@ -17,6 +17,17 @@ namespace inja { struct Template { std::vector nodes; std::string content; + + /// Return number of variables (total number, not distinct ones) in the template + int count_variables() { + int result {0}; + for (auto& n : nodes) { + if (n.flags == Node::Flag::ValueLookupDot || n.flags == Node::Flag::ValueLookupPointer) { + result += 1; + } + } + return result; + } }; using TemplateStorage = std::map; diff --git a/single_include/inja/inja.hpp b/single_include/inja/inja.hpp index cd8f473..40551d8 100644 --- a/single_include/inja/inja.hpp +++ b/single_include/inja/inja.hpp @@ -2280,6 +2280,17 @@ namespace inja { struct Template { std::vector nodes; std::string content; + + /// Return number of variables (total number, not distinct ones) in the template + int count_variables() { + int result {0}; + for (auto& n : nodes) { + if (n.flags == Node::Flag::ValueLookupDot || n.flags == Node::Flag::ValueLookupPointer) { + result += 1; + } + } + return result; + } }; using TemplateStorage = std::map; diff --git a/test/unit-renderer.cpp b/test/unit-renderer.cpp index 82682ca..fb2dc08 100644 --- a/test/unit-renderer.cpp +++ b/test/unit-renderer.cpp @@ -417,6 +417,17 @@ TEST_CASE("templates") { CHECK(env.render("{% for city in cities %}{% include \"city.tpl\" %}{% endfor %}", loop_data) == "0:Munich;1:New York;"); } + + SUBCASE("count variables") { + inja::Environment env; + inja::Template t1 = env.parse("Hello {{ name }}"); + inja::Template t2 = env.parse("{% if is_happy %}{{ name }}{% else %}{{ city }}{% endif %}"); + inja::Template t3 = env.parse("{% if at(name, test) %}{{ name }}{% else %}{{ city }}{{ upper(city) }}{% endif %}"); + + CHECK(t1.count_variables() == 1); + CHECK(t2.count_variables() == 3); + CHECK(t3.count_variables() == 5); + } } TEST_CASE("other-syntax") {