UNPKG

1.56 kBJavaScriptView Raw
1
2var voidElements = ['area','base','br','col','embed','hr','img','input','keygen','link','meta','param','source','track','wbr'];
3
4var Tag = module.exports = function Tag (name, attributes, content) {
5
6 if (name === undefined || name === null) {
7 throw new Error('You must supply a name for the tag.');
8 }
9
10 this.attributes = attributes || {};
11 this.content = content || '';
12 this.name = name;
13
14};
15
16Tag.prototype.render = function () {
17
18 var renderedAttributes = '',
19 opening = '',
20 closing = '';
21
22 // <form action="" method=""></form>
23 // <hr />
24 return this.renderOpening() + this.renderContent() + this.renderClosing();
25
26};
27
28Tag.prototype.renderOpening = function () {
29
30 var selfClosing = (voidElements.indexOf(this.name) >= 0)
31 ? ' /'
32 : '';
33
34 return '<' + this.name + '' + this.renderAttributes() + selfClosing + '>';
35
36};
37
38Tag.prototype.renderClosing = function () {
39
40 return (voidElements.indexOf(this.name) >= 0)
41 ? ''
42 : '</' + this.name + '>';
43
44};
45
46Tag.prototype.renderContent = function () {
47
48 return (this.content)
49 ? this.content
50 : '';
51
52};
53
54Tag.prototype.renderAttributes = function () {
55
56 var _this = this,
57 keys = Object.keys(this.attributes),
58 attributes = [];
59
60 if (!keys.length) {
61 return '';
62 }
63
64 keys.forEach(function (key) {
65 attributes.push(_this.renderAttribute(key, _this.attributes[key]));
66 });
67
68 return ' ' + attributes.join(' ');
69
70};
71
72Tag.prototype.renderAttribute = function (name, value) {
73
74 // handle non-value attributes such as disabled
75 if (value === true) {
76 return name;
77 }
78
79 return name + '="' + value + '"';
80
81};
\No newline at end of file