Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- if ($tod::nextid $= "") {
- $tod::nextid = 0;
- }
- function ____tod_escape(%input) {
- %length = strlen(%input);
- for (%i = 0; %i < %length; %i++) {
- %char = getSubStr(%input, %i, 1);
- // Not perfectly safe yet - doesn't escape the following:
- // ! @ $ % ( ) + { } [ ]
- switch$ (%char) {
- case "&": %output = %output @ "&";
- case "<": %output = %output @ "<";
- case ">": %output = %output @ ">";
- case "\"": %output = %output @ """;
- case "'": %output = %output @ "'";
- case "`": %output = %output @ "`";
- case " ": %output = %output @ " ";
- case "=": %output = %output @ "=";
- default: %output = %output @ %char;
- }
- }
- return %output;
- }
- function tod::compile(%template) {
- %index = 0;
- %length = strlen(%template);
- while (1) {
- %start = strpos(%template, "{{", %index);
- if (%start == -1) {
- %start = %length;
- }
- if (%start > %index) {
- %text = expandEscape(getSubStr(%template, %index, %start - %index));
- %code = %code @ "%_r=%_r@\"" @ %text @ "\";";
- }
- if (%start >= %length) {
- break;
- }
- %hair = "";
- %in_string = false;
- %end = -1;
- for (%i = %start + 2; %i < %length; %i++) {
- if (%in_string) {
- %char = getSubStr(%template, %i, 1);
- %hair = %hair @ %char;
- if (!%in_escape && %char $= "\"") {
- %in_string = false;
- } else {
- %in_escape = %char $= "\\";
- }
- } else {
- %char = getSubStr(%template, %i, 1);
- if (%char $= "}" && getSubStr(%template, %i + 1, 1) $= "}") {
- %end = %i;
- break;
- }
- if (%char $= "#") {
- %hair = %hair @ "%_d.";
- } else {
- if (%char $= "\"") {
- %in_string = true;
- }
- %hair = %hair @ %char;
- }
- }
- }
- if (%end == -1) {
- error("ERROR: Unclosed {{ at " @ %start);
- return "";
- }
- %hair = trim(%hair);
- if (%hair $= "") {
- error("ERROR: Empty {{ expression }} at " @ %start);
- return "";
- }
- if (getSubStr(%hair, 0, 1) $= ":") {
- %fun = getSubStr(firstWord(%hair), 1, strlen(%hair));
- %arg = restWords(%hair);
- switch$ (%fun) {
- case "ts": %code = %code @ %arg;
- case "raw": %code = %code @ "%_r=%_r@" @ %hair @ ";";
- case "end": %code = %code @ "}";
- case "if": %code = %code @ "if(" @ %arg @ "){";
- case "for": %code = %code @ "for(" @ %arg @ "){";
- case "while": %code = %code @ "raw(" @ %arg @ "){";
- default:
- error("ERROR: Unknown {{ :function }} at " @ %start);
- return "";
- }
- } else {
- %code = %code @ "%_r=%_r@____tod_escape(" @ %hair @ ");";
- }
- %index = %end + 2;
- }
- %name = "____tod_template_" @ $tod::nextid;
- eval("function " @ %name @ "(%_d){" @ %code @ "return %_r;}");
- if (!isFunction(%name)) {
- error("ERROR: Failed to compile template");
- return "";
- }
- $tod::nextid = ($tod::nextid + 1) | 0;
- return %name;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement