Skip to content

Instantly share code, notes, and snippets.

@jdan
Last active August 29, 2015 14:01
Show Gist options
  • Save jdan/d8c34120379d1c7f27e1 to your computer and use it in GitHub Desktop.
Save jdan/d8c34120379d1c7f27e1 to your computer and use it in GitHub Desktop.

domino

quick-n-dirty HTML markup generator

examples

var dom = require('./domino');
dom.ul.li.span.class('note')

produces

<ul>
  <li>
    <span class="note"></span>
  </li>
</ul>

dom.ul.li.count(5).class('item').p

produces

<ul>
  <li class="item">
    <p></p>
  </li>
  <li class="item">
    <p></p>
  </li>
  <li class="item">
    <p></p>
  </li>
  <li class="item">
    <p></p>
  </li>
  <li class="item">
    <p></p>
  </li>
</ul>
var tags = require('./tags');
function Domino(tag, ancestors, opts) {
this.tag = tag || '';
this.ancestors = ancestors || [];
this.parent = this.ancestors[0];
this.nodeCount = 1;
this.nodeId = null;
this.classList = [];
}
/* Metaprogramming for each tag */
tags.forEach(function (tag) {
Object.defineProperty(Domino.prototype, tag, {
get: function () {
return new Domino(tag, [this].concat(this.ancestors), {});
}
});
});
Domino.prototype.count = function (count) {
this.nodeCount = count;
return this;
};
Domino.prototype.id = function (id) {
this.nodeId = id;
return this;
};
Domino.prototype.class = Domino.prototype.addClass = function (className) {
this.classList.push(className);
return this;
};
Domino.prototype.toString = function (inside) {
inside = inside || '';
/* calculate the padding for nested tags */
var padding = new Array(this.ancestors.length).join(' ');
/* generate an opening tag */
var open = '<' + this.tag;
/* add the id if one exists */
if (this.nodeId) {
open += ' id="' + this.nodeId + '"';
}
/* add the classList */
if (this.classList.length > 0) {
open += ' class="' + this.classList.join(' ') + '"';
}
open += '>';
/* generate a closing tag */
var close = '</' + this.tag + '>';
var markup;
if (inside.match(/^\s+/g)) {
/* we have inner tags, place tags on their own line */
markup = [padding + open, inside, padding + close].join('\n');
} else {
/* otherwise, the opening and closing tags share a line */
markup = padding + open + inside + close;
}
/* multiply by count */
if (this.nodeCount > 1) {
markup = new Array(this.nodeCount + 1).join(markup + '\n').slice(0, -1);
}
return (this.parent.ancestors.length) ? this.parent.toString(markup) : markup;
};
module.exports = new Domino();
module.exports = [
'ul',
'li',
'p',
'span'
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment