aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/template.c18
-rw-r--r--tests/test_template.c12
2 files changed, 29 insertions, 1 deletions
diff --git a/src/template.c b/src/template.c
index 9555206..f85db25 100644
--- a/src/template.c
+++ b/src/template.c
@@ -645,16 +645,32 @@ struct unja_object *filter_trim(struct unja_object *obj) {
struct unja_object *filter_lower(struct unja_object *obj) {
assert(obj->type == OBJ_STRING);
- for (int i=0; i < strlen(obj->string); i++) {
+ int len = strlen(obj->string);
+ for (int i=0; i < len; i++) {
obj->string[i] = tolower(obj->string[i]);
}
return obj;
}
+struct unja_object *filter_wordcount(struct unja_object *obj) {
+ assert(obj->type == OBJ_STRING);
+ int len = strlen(obj->string);
+ int word_count = 1;
+ for (int i=0; i < len; i++) {
+ if (isspace(obj->string[i])) {
+ word_count++;
+ }
+ }
+
+ object_free(obj);
+ return make_int_object(word_count);
+}
+
struct hashmap *default_filters() {
struct hashmap *filters = hashmap_new();
hashmap_insert(filters, "trim", filter_trim);
hashmap_insert(filters, "lower", filter_lower);
+ hashmap_insert(filters, "wordcount", filter_wordcount);
return filters;
}
diff --git a/tests/test_template.c b/tests/test_template.c
index 51c8fad..6b2ca12 100644
--- a/tests/test_template.c
+++ b/tests/test_template.c
@@ -472,4 +472,16 @@ TEST(filter_lower) {
free(output);
}
+TEST(filter_wordcount) {
+ char *input = "{{ \"Hello World. How are we?\" | wordcount }}";
+ char *output = template_string(input, NULL);
+ assert_str(output, "5");
+ free(output);
+
+ input = "{% if \"Hello World. How are we?\" | wordcount > 4 %}1{% endif %}";
+ output = template_string(input, NULL);
+ assert_str(output, "1");
+ free(output);
+}
+
END_TESTS \ No newline at end of file