Skip to content

Instantly share code, notes, and snippets.

@Evantm
Created March 11, 2019 08:13
Show Gist options
  • Save Evantm/cd21df18bdf9c3222e31bf68ecc36953 to your computer and use it in GitHub Desktop.
Save Evantm/cd21df18bdf9c3222e31bf68ecc36953 to your computer and use it in GitHub Desktop.
Automatic text templates from JSON. Version Alpha. Thoroughly untested
<!DOCTYPE html>
<html>
<head>
<title>Evan's Templating Site</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script id="json" src="template.json"></script>
</head>
<body>
</body>
<script type="text/javascript">
String.prototype.interpolate = function(params) { //fuking magic
const names = Object.keys(params);
const vals = Object.values(params);
return new Function(...names, `return \`${this}\`;`)(...vals);
}
function copyToClipboard(text){
var dummy = document.createElement("input");
document.body.appendChild(dummy);
dummy.setAttribute('value', text);
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
function ask_user(template_string, variables){
console.log(template_string,variables)
var variables_dict = {}
for (var i = template_string.length - 1; i >= 0; i--) {
var value = prompt(template_string[i])
variables_dict[template_string[i]] = value
}
const result = variables.interpolate(variables_dict);
copyToClipboard(result)
console.log(result)
}
for (var i = templates.length - 1; i >= 0; i--) {
var section = document.createElement("SECTION");
var header = document.createElement("H1");
var header_text = document.createTextNode(templates[i].type)
header.appendChild(header_text);
section.appendChild(header)
for (var j = templates[i].template_list.length - 1; j >= 0; j--) {
var variables = templates[i].template_list[j].variables
var template = templates[i].template_list[j].template
var btn = document.createElement("BUTTON");
btn.className = "btn btn-primary"
const f = function() { ask_user(variables,template);}
btn.addEventListener("click",f)
var text = document.createTextNode(templates[i].template_list[j].label);
btn.appendChild(text);
section.appendChild(btn);
}
document.body.appendChild(section);
}
</script>
</html>
var templates = [
{
"type": "Students",
"template_list": [
{
"label": "passoword reset",
"template": "Hello ${name}",
"variables": [
"name"
]
}
]
},
{
"type": "Staff",
"template_list": [
{
"label": "Something Complicated",
"template": "Hello ${student_name}, my name is ${my_name}",
"variables": [
"student_name", "my_name"
]
}
]
}
]
@Evantm
Copy link
Author

Evantm commented Mar 11, 2019

Bug with multiple templates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment