Skip to content

Instantly share code, notes, and snippets.

@RubaXa
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RubaXa/e9056762c3c6b239cc9a to your computer and use it in GitHub Desktop.
Save RubaXa/e9056762c3c6b239cc9a to your computer and use it in GitHub Desktop.
AbsurdTpl — JavaScript micro-micro-templating, v0.3.1
(function () { 'use strict';
var indent = 0, tags = [], close, begin, rshort = /^(img|input|hr|br)$/;
window['absurdTpl'] = function _(name, template) {
return _[name] = Function('ctx', ('var buf = "";\n' + (template || name).toString().split('\n').slice(1, -1).map(function (line, idx, lines) {
return line.replace(/\/\/.+|\/\*.*?\*\//g, '')
.replace(/~([\w+_-]+)/i, 'buf += absurdTpl["$1"]')
.replace(/^(\s*)(?:([a-z]+[0-9]*)((?:\.[a-z_-]+[\w_-]+)*)((?:\[.*?\])*)(?:\s+\|\s+(.*?))?($|;)|.)/, function (_, ind, tag, classes, attrs, html) {
begin = (indent >= ind.length) && (close = tags.splice(0, indent/ind.length).filter(isNaN)).length ? 'buf += "</' + close.join('></') + '>";\n' : '';
indent = ind.length;
!rshort.test(tag) && tags.unshift(tag || 0);
return begin + (tag ? 'buf += "<' + tag
+ (classes ? ' class=\\"' + classes.substr(1).replace(/\./, ' ') + '\\"' : '')
+ (attrs ? attrs.replace(/\[([^=]+)=([^\]]*)\]/g, ' $1=\\"" + $2 + "\\"') : '')
+ (html ? '>" + ' + html + ';\n' : '>";\n')
: _);
});
}).join('') + (tags.length ? '\nbuf += "</' + tags.filter(isNaN).splice(0, 1e8).join('></') + '>";' : '') + '\nreturn buf;').replace(/";\n+\s*buf \+= "/g, ''));
};
})();
@RubaXa
Copy link
Author

RubaXa commented Jun 8, 2014

Just for fun

Don't use it!1

Syntax

div.foo.bar[attr=value] | expression

  • div — node name
  • foo — first class name
  • bar — second class name
  • [attr=value] — attributes
  • expression — javascript expression

Example

absurdTpl("formItem", function (ctx) {
    div.form-element
        label | ctx.label + ":";
        input[value=ctx.value];
});

var result = absurdTpl("form", function (ctx) {
    // This comment
    form[action="/"][method="post"];
        h2 | "Simple form";
        ctx.items.forEach(function (inp) {
            ~formItem(inp); // call block
        });
        hr;
        button[type="submit"] | "Send";
});

var html = result({
    items: [{ label: "E-mail", value: "trash@rubaxa.org" }]
});

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