+impl ParsedTemplate {
+ pub fn render(&self, context: &TemplateContext) -> String {
+ ParsedTemplate::render_tokens(&self.tokens, context)
+ }
+
+ pub fn render_tokens(tokens: &Vec<Token>, context: &TemplateContext) -> String {
+ let mut rendered_template: String = String::new();
+ for token in tokens {
+ match token {
+ Token::Text(contents) => rendered_template.push_str(&contents),
+ Token::DisplayDirective { content } => {
+ match TemplateContextGetter::get(context, &content) {
+ Some(value) => rendered_template.push_str(&value.render()),
+ None => panic!("{} is not a valid key", content)
+ }
+ },
+ Token::ConditionalDirective { condition, children} => {
+ let mut negator = false;
+ let mut condition = condition.to_string();
+ if condition.starts_with('!') {
+ negator = true;
+ condition = condition[1..].to_string();
+ }
+ match TemplateContextGetter::get(context, &condition) {
+ Some(TemplateValue::Bool(value)) => {
+ if negator ^ value {
+ rendered_template.push_str(&ParsedTemplate::render_tokens(children, context))
+ }
+ },
+ _ => panic!("{} is not a boolean value", condition)
+ }
+ },
+ Token::IteratorDirective { collection, member_label, children } => {
+ match TemplateContextGetter::get(context, &collection) {
+ Some(TemplateValue::Collection(collection)) => {
+ for member in collection {
+ let mut child_context = context.clone();
+ child_context.insert(
+ member_label.to_string(),
+ TemplateValue::Context(member)
+ );
+ rendered_template.push_str(&ParsedTemplate::render_tokens(&children, &child_context))
+ }
+ },
+ _ => panic!("{} is not a collection", collection)
+ }
+ }
+ }
+ }
+ rendered_template
+ }
+}
+