1 |
|
2 | var voidElements = ['area','base','br','col','embed','hr','img','input','keygen','link','meta','param','source','track','wbr'];
|
3 |
|
4 | var 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 |
|
16 | Tag.prototype.render = function () {
|
17 |
|
18 | var renderedAttributes = '',
|
19 | opening = '',
|
20 | closing = '';
|
21 |
|
22 |
|
23 |
|
24 | return this.renderOpening() + this.renderContent() + this.renderClosing();
|
25 |
|
26 | };
|
27 |
|
28 | Tag.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 |
|
38 | Tag.prototype.renderClosing = function () {
|
39 |
|
40 | return (voidElements.indexOf(this.name) >= 0)
|
41 | ? ''
|
42 | : '</' + this.name + '>';
|
43 |
|
44 | };
|
45 |
|
46 | Tag.prototype.renderContent = function () {
|
47 |
|
48 | return (this.content)
|
49 | ? this.content
|
50 | : '';
|
51 |
|
52 | };
|
53 |
|
54 | Tag.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 |
|
72 | Tag.prototype.renderAttribute = function (name, value) {
|
73 |
|
74 |
|
75 | if (value === true) {
|
76 | return name;
|
77 | }
|
78 |
|
79 | return name + '="' + value + '"';
|
80 |
|
81 | }; |
\ | No newline at end of file |