Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add template engine example app #504

Merged
merged 5 commits into from
Dec 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/runExamples.du
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ import "isPalindrome.du";
import "factorial.du";
import "pathWalker.du";
import "structured_logger.du";
import "template_engine.du";
52 changes: 52 additions & 0 deletions examples/template_engine.du
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import System;

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

init(private tmpl, private klass) {}

// render parses the given template and class and
// matches the fields in the class to the template
// fields and replaces them with the class values.
render() {
const classAttrs = this.klass.getAttributes()["properties"];
var rendered = this.tmpl;

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

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

return rendered;
}
}

// Person is a class used to hold data to be passed
// to the template engine.
class Person {
init(var name, var age) {}
}

// main
{
const tmpl = "Hello {name}! You are {age} years old.";
const p = Person("John", 12);

const t = Template(tmpl, p);

print(t.render());
}