From 9acb03e669e20180b9bc95ca02b21460761fef87 Mon Sep 17 00:00:00 2001 From: "Rafael G. Martins" Date: Sun, 3 Jul 2016 03:25:12 +0200 Subject: template-parser: renderer: implemented 'else' support in templates yeah, this is stupid. after more than 320 commits and 26 releases, we finally support the 'else' statement in the template engine. I don't know if I'm dumb or what, but it took me that long to find a "simple" solution to this basic issue. yep, no more `{% ifdef FOO %}...{% endif %}{% ifndef FOO %}...{% endif %}` blocks. but seriously, who cares?! :/ --- src/renderer.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) (limited to 'src/renderer.c') diff --git a/src/renderer.c b/src/renderer.c index 0f71ba7..351dfb1 100644 --- a/src/renderer.c +++ b/src/renderer.c @@ -188,6 +188,7 @@ blogc_render(sb_slist_t *tmpl, sb_slist_t *sources, sb_trie_t *config, bool list bool if_not = false; bool inside_block = false; bool evaluate = false; + bool valid_else = false; int cmp = 0; @@ -343,13 +344,23 @@ blogc_render(sb_slist_t *tmpl, sb_slist_t *sources, sb_trie_t *config, bool list if_count++; continue; } + if ((stmt->type == BLOGC_TEMPLATE_ELSE_STMT) && + (if_count == 0)) + { + // this is somewhat complex. only an else statement + // right after a non evaluated block should be considered + // valid, because all the inner conditionals were just + // skipped, and all the outter conditionals evaluated + // to true. + valid_else = true; + break; + } if (stmt->type == BLOGC_TEMPLATE_ENDIF_STMT) { if (if_count > 0) { if_count--; continue; } - if (if_count == 0) - break; + break; } } } @@ -358,7 +369,41 @@ blogc_render(sb_slist_t *tmpl, sb_slist_t *sources, sb_trie_t *config, bool list if_not = false; break; + case BLOGC_TEMPLATE_ELSE_STMT: + if_count = 0; + if (!valid_else) { + + // at this point we can just skip anything, counting the + // number of 'if's, to know how many 'endif's we need to + // skip as well. + while (1) { + tmp = tmp->next; + stmt = tmp->data; + if ((stmt->type == BLOGC_TEMPLATE_IF_STMT) || + (stmt->type == BLOGC_TEMPLATE_IFDEF_STMT) || + (stmt->type == BLOGC_TEMPLATE_IFNDEF_STMT)) + { + if_count++; + continue; + } + // no need to handle else statements here, because every + // if should have an endif. + if (stmt->type == BLOGC_TEMPLATE_ENDIF_STMT) { + if (if_count > 0) { + if_count--; + continue; + } + break; + } + } + } + valid_else = false; + break; + case BLOGC_TEMPLATE_ENDIF_STMT: + // any endif statement should invalidate valid_else, to avoid + // propagation to outter conditionals. + valid_else = false; if (if_count > 0) if_count--; break; -- cgit v1.2.3-18-g5258