Skip to content

Instantly share code, notes, and snippets.

@alexeypegov
Created April 14, 2012 09:28
Show Gist options
  • Save alexeypegov/2383142 to your computer and use it in GitHub Desktop.
Save alexeypegov/2383142 to your computer and use it in GitHub Desktop.
some handy html gen function & string format extension function
// usage: _('#id.class1.class2[data-b=b]', 'test') -> <div id="id" class="class1 class2" data-b="b">test</div>
// or: _('a.link', {href: 'http://www.example.com'}, 'Click me') -> <a class="link" href="http://www.example.com">Click me</a>
_ = function(text, content_or_attrs, content) {
var result = "", id = false, cls = false, p = false, tag = false;
var b = "";
for (var i = 0; i < text.length; i++) {
var ch = text.charAt(i);
if (ch == '#' && !p) {
result = b.length > 0 ? '<' + b + ' id="': '<div id="';
tag = b.length > 0 ? b : 'div';
b = "";
id = true;
continue;
} else if (ch == '.' && !p) {
result += id ? b + '" class="' : cls ? b + ' ' : b.length > 0 ? '<' + b + ' class="' : '<div class="';
tag = !id && !tag ? (b.length > 0 ? b : 'div') : tag;
b = "";
id = false;
cls = true;
continue;
} else if (ch == '[') {
result += id ? b + '"' : cls ? b + '"' : '<' + b;
tag = !id && !cls && !tag ? (b.length > 0 ? b : 'div') : tag;
id = false;
cls = false;
p = true;
b = "";
continue;
} else if (ch == '=') {
result += ' ' + b + '="';
b = "";
continue;
} else if (ch == ',') {
result += b + '"';
b = "";
continue;
} else if (ch == ']') {
result += b + '"';
p = false;
b = "";
continue;
}
b += ch;
}
tag = !tag && !id && !cls ? b : tag;
result = (b.length > 0 ? (id || cls ? result + b + '"' : '<' + b) : result);
var has_attrs = typeof(content_or_attrs) != 'string' && typeof(content_or_attrs) != "function";
var _content = has_attrs ? content : content_or_attrs;
if (has_attrs) {
for (var key in content_or_attrs) {
if (result[result.length - 1] != ' ') result += " ";
result += key + '="' + content_or_attrs[key] + '"';
}
}
if (_content == undefined) {
result += '/>';
} else {
if (typeof _content == "function") {
result += '>';
_content(function(text) { result += text });
result += '</' + tag + '>';
} else {
result += '>' + _content + '</' + tag + '>';
}
}
return result;
};
// usage: "the next {0} will be {1}".format("value", "replaced")
String.prototype.format = function() {
var s = this;
for (var i = 0; i < arguments.length; i++) {
s = s.replace("{" + i + "}", arguments[i]);
}
return s;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment