Skip to content

Commit

Permalink
Make HTML templates output Javascript, part 1. #829
Browse files Browse the repository at this point in the history
  • Loading branch information
ccd0 committed Jul 25, 2019
1 parent cba171b commit c64acea
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions tools/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ tools.multiline = function(text) {
return text.replace(/\n+/g, '\n').split(/^/m).map(JSON.stringify).join('+').replace(/"\+"/g, '\\\n');
};

// Convert JSON object to Coffeescript expression (via embedded JS).
var constExpression = data => '`' + JSON.stringify(data).replace(/`/g, '\\`') + '`';
// Convert JSONify-able object to Javascript expression.
var constExpression = data => JSON.stringify(data).replace(/`/g, '\\`');

function TextStream(text) {
this.text = text;
Expand Down Expand Up @@ -151,11 +151,11 @@ Placeholder.prototype.build = function() {
throw new Error(`JavaScript in template is not an expression (${expr})`);
}
switch(this.type) {
case '$': return `\`E(${expr})\``; // $ : escaped text
case '&': return `\`(${expr}).innerHTML\``; // & : contents of HTML element or template (of form {innerHTML: "safeHTML"})
case '@': return `\`E.cat(${expr})\``; // @ : contents of array of HTML elements or templates (see src/General/Globals.coffee for E.cat)
case '$': return `E(${expr})`; // $ : escaped text
case '&': return `(${expr}).innerHTML`; // & : contents of HTML element or template (of form {innerHTML: "safeHTML"})
case '@': return `E.cat(${expr})`; // @ : contents of array of HTML elements or templates (see src/General/Globals.coffee for E.cat)
case '?':
return `(if \`(${expr})\` then ${this.args[1] || '""'} else ${this.args[2] || '""'})`; // ? : conditional expression
return `((${expr}) ? ${this.args[1] || '""'} : ${this.args[2] || '""'})`; // ? : conditional expression
}
throw new Error(`Unrecognized placeholder type (${this.type})`);
};
Expand All @@ -168,11 +168,11 @@ tools.html = function(template) {
if (stream.text) {
throw new Error(`Unexpected characters in template (${stream.text}): ${template}`);
}
return `(innerHTML: ${output})`;
return `(innerHTML: \`${output}\`)`;
};

tools.assert = function(statement) {
return `throw new Error 'Assertion failed: ' + ${constExpression(statement)} unless ${statement}`;
return `throw new Error 'Assertion failed: ' + \`${constExpression(statement)}\` unless ${statement}`;
};

function includesDir(templateName) {
Expand Down

0 comments on commit c64acea

Please sign in to comment.