Skip to content

Commit

Permalink
update template engine example
Browse files Browse the repository at this point in the history
Signed-off-by: Brian Downs <brian.downs@gmail.com>
  • Loading branch information
briandowns committed Dec 30, 2021
1 parent 4ca46ac commit a06ee77
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions examples/template_engine.du
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import System;

const LEFT_BRACE = "{";
const RIGHT_BRACE = "}";

// Template is a simple template rendering engine.
class Template {
private tmpl;
private klass;
private rendered;
var LEFT_BRACE = "{";
var RIGHT_BRACE = "}";

init(tmpl, klass) {
this.tmpl = tmpl;
Expand All @@ -19,22 +15,26 @@ class Template {
// fields and replaces them with the class values.
render() {
const classAttrs = this.klass.getAttributes()["properties"];
this.rendered = this.tmpl;
var rendered = this.tmpl;

classAttrs.forEach(def(attr) => {
const attrVal = this.klass.getAttribute(attr);
const tmplField = LEFT_BRACE+attr+RIGHT_BRACE;
const tmplField = "{}{}{}".format(
Template.LEFT_BRACE,
attr,
Template.RIGHT_BRACE
);

if (this.rendered.contains(tmplField)) {
if (rendered.contains(tmplField)) {
if (type(attrVal) != "string") {
this.rendered = this.rendered.replace(tmplField, attrVal.toString());
rendered = rendered.replace(tmplField, attrVal.toString());
} else {
this.rendered = this.rendered.replace(tmplField, attrVal);
rendered = rendered.replace(tmplField, attrVal);
}
}
});

return this.rendered;
return rendered;
}
}

Expand All @@ -54,5 +54,5 @@ class Person {

const t = Template(tmpl, p);

print("{}".format(t.render()));
print(t.render());
}

0 comments on commit a06ee77

Please sign in to comment.