<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TPL Engine</title>
</head>
<body><div id="output"></div>
<script type="text/javascript">
// Преобразование содержимого объекта в текст для вставки в HTML-код.
// Параметры:
// obj - конвертируемый объект.
// Пример использовния :
// var obj = {
// a: 1
// , b: null
// , c: undefined
// , d: 'text<br/>text'
// , e: [1,2,3]
// , f: {objkey: 'objvalue'}
// , g: function () {console.log(1);}
// , h: new Date()
// , i: true
// , j: new RegExp('a{1,2}')
// , k: new Error('some error')
// , l: NaN
// , m: []
// , n: {}
// };
// convertObjectToHtmlText(obj);
// Возвращает отформатированную строку, представляющую содержимое объекта, пригодную для вставки в HTML-код.
// Возвращает сообщение об ошибке, если в функцию не был передан объект.
// Преобразовать содержимое объекта в текст для вставки в HTML-код
function convertObjectToHtmlText (obj, options) {
var indentString = ' '
, newLine = '<br />'
, newLineJoin = ',' + newLine;
if (options && options.rawHTML) {
indentString = ' '; // 4 пробела
newLine = '\n';
newLineJoin = ',' + newLine;
}
// Функция определения типа объекта
function objectType (obj) {
var types = {
'null': 'null'
, 'undefined': 'undefined'
, 'number': 'number'
, 'boolean': 'boolean'
, 'string': 'string'
, '[object Function]': 'function'
, '[object RegExp]': 'regexp'
, '[object Array]': 'array'
, '[object Date]': 'date'
, '[object Error]': 'error'
};
return types[typeof obj] || types[Object.prototype.toString.call(obj)] || (obj ? 'object' : 'null');
}
// Функция определения числа элементов в объекте
function objectSize (obj) {
var size = 0
, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {size++;}
}
return size;
}
// Привести элемент к нужному формату
function formatElement (element, indent, indentFromArray) {
indentFromArray = indentFromArray || '';
switch (objectType(element)) {
case 'null': return indentFromArray + 'null';
case 'undefined': return indentFromArray + 'undefined';
case 'number': return indentFromArray + element;
case 'boolean': return indentFromArray + (element ? 'true' : 'false');
case 'string': if (options && options.rawHTML) {
return indentFromArray + '"'
+ element
+ '"';
} else {
return indentFromArray + '"'
+ element.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/, '"')
.replace(/'/g, ''')
+ '"';
}
case 'array': return indentFromArray + (element.length > 0 ? '[' + newLine + formatArray(element, indent) + indent + ']' : '[]');
case 'object': return indentFromArray + (objectSize(element) > 0 ? '{' + newLine + formatObject(element, indent) + indent + '}' : '{}');
default: return indentFromArray + element.toString();
}
}
// Привести массив к нужному формату
function formatArray (array, indent) {
var index
, length = array.length
, value = [];
indent += indentString;
for (index = 0; index < length; index += 1) {
value.push(formatElement(array[index], indent, indent));
}
return value.join(newLineJoin) + newLine;
}
// Привести объект к нужному формату
function formatObject (object, indent) {
var value = []
, property;
indent += indentString;
for (property in object) {
if (object.hasOwnProperty(property)) {
if (options && options.rawHTML) {
value.push(indent + '"' + property + '": ' + formatElement(object[property], indent));
} else {
value.push(indent + '"' + property + '": ' + formatElement(object[property], indent));
}
}
}
return value.join(newLineJoin) + newLine;
}
if (typeof obj === 'object') {return formatElement(obj, '');
} else {throw new Error ('No javascript object has been provided to function convertObjectToHtmlText (obj) {...}');
}
}
Function.prototype.trace = function () {
var trace = []
, current = this;
while (current) {
trace.push(current.signature());
current = current.caller;
}
return trace;
};
Function.prototype.signature = function () {
var signature = {
name: this.getName()
, params: []
, toString: function () {
var params = ''
, i = 0
, len = this.params.length
, last = len - 1;
for (; i < len; i++) {
if (typeof this.params[i] === 'object') {
params += convertObjectToHtmlText(this.params[i], {rawHTML: true});
} else if (typeof this.params[i] === 'string') {
params += '"' + this.params[i] + '"';
} else {
params += this.params[i];
}
if (len !== 1 && last !== i) {
params += ', ';
}
}
return this.name + '(' + params + ')';
}
};
if (this.arguments) {
for (var i = 0, len = this.arguments.length; i < len; i++) {
signature.params.push(this.arguments[i]);
}
}
return signature;
};
Function.prototype.getName = function () {
if (this.name) {
return this.name;
}
var definition = this.toString().split('\n')[0]
, exp = /^function ([^\s(]+).+/;
if (exp.test(definition)) {
return definition.split('\n')[0].replace(exp, '$1') || 'anonymous';
}
return 'anonymous';
};
function getTypeOf (value) {
if (value === window) {return 'window';}
if (value === null) {return 'null';}
if (value === undefined) {return 'undefined';}
if (value !== value) {return 'nan';}
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
function error (message, value) {
var trace = arguments.callee.trace()
, formattedTrace = ''
, i = 0
, len = trace.length
, last = len - 1;
for (; i < len; i++) {
formattedTrace = trace[i] + ';';
if (len !== 1 && last !== i) {
formattedTrace += '\n';
}
}
if (arguments.length === 2) {
if (typeof value === 'object') {
value = convertObjectToHtmlText(value, {rawHTML: true});
}
if (typeof value === 'string' && value.length === 0) {
value = '""';
}
message += ' ' + value + '\n\nStack trace\n\n' + formattedTrace;
}
if (console && console.error) {
console.error(message);
} else {
throw new Error(message);
}
}
;(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(factory);
} else if (typeof module === "object" && typeof module.exports === "object") {
module.exports = factory();
} else {
global.TPL = factory();
}
})(this, function () {
// Usage:
// console.log( new TPL.Template("<div>Total: {{= value }}<div>", {delimiters: ["{{", "}}"]}).render({value: "<span>15</span>"}) );
// console.log( new TPL.Template("<div>Total: {{- block('<div>{{= value }}</div>', {delimiters: ['{{', '}}']}, {value: value}) }}<div>", {delimiters: ["{{", "}}"]}).render({block: TPL.block, value: "<span>15</span>"}) );
// Options:
// delimiters - characters to use for open and close delimiters
// rmWhitespace - remove whitespace between HTML-tags
// Tags:
// <% - scriptlet tag for control-flow, no output
// <%% - outputs raw template part
// <%- - outputs the raw unescaped value into the template
// <%= - outputs the HTML escaped value into the template
// <%# - comment tag, no execution, no output
// %> - plain ending tag
// Block:
// "<div><%- block('<div><%= value %></div>', {delimiters: ['<%', '%>']}, {value: outerValue}) %></div>"
function Template (templateString, settingsObject) {
var dummy = {render: function () {return '';}};
if (typeof templateString !== 'string') {error('Template must be a string, but it is: ', templateString); return dummy;}
if (arguments.length === 2) {
if (getTypeOf(settingsObject) !== 'object') {error('Settings must be an object, but it is: ', settingsObject); return dummy;}
if (!('delimiters' in settingsObject || 'rmWhitespace' in settingsObject)) {error('Settings must contains property "delimiters" or property "rmWhitespace", but it is: ', settingsObject); return dummy;}
if ('delimiters' in settingsObject) {
if (getTypeOf(settingsObject.delimiters) !== 'array') {error('Property "delimiters" must be an array, but it is: ', settingsObject.delimiters); return dummy;}
if (settingsObject.delimiters.length !== 2 || typeof settingsObject.delimiters[0] !== 'string' || typeof settingsObject.delimiters[1] !== 'string') {
error('Property "delimiters" must be an array with 2 strings, but it is: ', settingsObject.delimiters); return dummy;
}
}
if ('rmWhitespace' in settingsObject && getTypeOf(settingsObject.rmWhitespace) !== 'boolean') {error('Property "rmWhitespace" must be a boolean, but it is: ', settingsObject.rmWhitespace); return dummy;}
}
var delimiters = ["<%", "%>"]
, rmWhitespace = false; // removeWhitespace
if (settingsObject) {
if ('delimiters' in settingsObject) {delimiters = settingsObject.delimiters;}
if ('rmWhitespace' in settingsObject) {rmWhitespace = settingsObject.rmWhitespace;}
}
var renderFunction = createRenderFunction(templateString, delimiters);
return {render: function (dataObject) {
var renderedHTML = renderFunction(dataObject, escapeHtmlFunction);
if (rmWhitespace === true) {
renderedHTML = removeSpaces(renderedHTML);
}
return renderedHTML;
}};
}
function removeSpaces (renderedHTML) {
return renderedHTML.replace(/\r/g, "") // Remove carriage return symbols
.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") // Trim space: \s, BOM: \uFEFF, NBSP: \xA0
.replace(/\s+(<[^%(?:span|b|strong|i|em|del|s|u|a|sub|sup|small|abbr|img)])/g, "$1") // Remove spaces between start tag and content
.replace(/([^%(?:span|b|strong|i|em|del|s|u|a|sub|sup|small|abbr|img)]>)\s+/g, "$1") // Remove spaces between end tag and content
.replace(/\s+/g, " "); // Remove spaces inside content
}
function createMatchRegExp (delimiters) { // delimiters = ["<%", "%>"]
var openDelimiter = delimiters[0] // <%
, closeDelimiter = delimiters[1] // %>
, stringInsideDelimiters = "([\\s\\S]+?)" // any string
, tags = {
rawTemplatePart: openDelimiter + "%" + stringInsideDelimiters + closeDelimiter // <%% "<div><%= value %></div>" %> --> "<div><%= value %></div>"
, rawHtmlUnescapedValue: openDelimiter + "-" + stringInsideDelimiters + closeDelimiter // <%- "1<br />2" %> --> "1<br />2"
, htmlEscapedValue: openDelimiter + "=" + stringInsideDelimiters + closeDelimiter // <%= "1<br />2" %> --> "1<br />2"
, comment: openDelimiter + "#" + stringInsideDelimiters + closeDelimiter // <%# any comment %> --> ""
, evaluate: openDelimiter + stringInsideDelimiters + closeDelimiter // <% if (value === 1) { %>one<% } %> --> "one"
}
, matchRegExp = new RegExp([
tags.rawTemplatePart // Important!!! Must be first!
, tags.rawHtmlUnescapedValue
, tags.htmlEscapedValue
, tags.comment
, tags.evaluate // Important!!! Must be last!
].join("|") + "|$", "g"); // /<%%([\s\S]+?)%>|<%-([\s\S]+?)%>|<%=([\s\S]+?)%>|<%#([\s\S]+?)%>|<%([\s\S]+?)%>|$/g
return matchRegExp;
}
function createRenderFunction (templateString, delimiters) {
var matchRegExp = createMatchRegExp(delimiters)
, renderFunction;
try {
renderFunction = new Function ("_dataObject_", "_escapeHtmlFunction_" // ) {
, "if (!_dataObject_) {_dataObject_ = {};}" + "\n"
+ "var _parsedTemplateString_ = '';" + "\n"
+ "with (_dataObject_) {" + "\n"
+ "_parsedTemplateString_ += '" + (function(){
var resultString = ""
, index = 0;
templateString.replace(matchRegExp, function (
match
, rawTemplatePartCodeString
, rawUnescapedValueCodeString
, htmlEscapedValueCodeString
, commentCodeString
, evaluateCodeString
, offset
) {
resultString += escapeString(templateString.slice(index, offset));
index = offset + match.length;
if (rawTemplatePartCodeString) {
resultString += delimiters[0] + escapeString(rawTemplatePartCodeString) + delimiters[1];
} else if (rawUnescapedValueCodeString) {
resultString += "'" + "\n"
+ "+ (function _rawUnescapedValue_ () {" + "\n"
+ "var _value_ = " + rawUnescapedValueCodeString + ";" + "\n"
+ "if (_value_ === undefined || _value_ === null) {return '';} else {return _value_;}" + "\n"
+ "})()" + "\n"
+ "+ '";
} else if (htmlEscapedValueCodeString) {
resultString += "'" + "\n"
+ "+ (function _htmlEscapedValue_ () {" + "\n"
+ "var _value_ = " + htmlEscapedValueCodeString + ";" + "\n"
+ "if (_value_ === undefined || _value_ === null) {return '';} else {return _escapeHtmlFunction_(_value_);}" + "\n"
+ "})()" + "\n"
+ "+ '";
} else if (commentCodeString) {
// Do nothing
} else if (evaluateCodeString) {
resultString += "';" + "\n"
+ evaluateCodeString + "\n"
+ "_parsedTemplateString_ += '";
}
return match;
});
return resultString;
})()
+ "';" + "\n"
+ "}" + "\n"
+ "return _parsedTemplateString_;"
// }
);
} catch (err) {
error(err.message += ' while compiling template:\n', templateString);
return function () {return '';};
}
return renderFunction;
}
function escapeString (string) {
var escapeCharacters = {
"'": "\\'"
, "\\": "\\\\"
, "\r": "\\r"
, "\n": "\\n"
, "\u2028": "\\u2028"
, "\u2029": "\\u2029"
};
return string.replace(/\\|'|\r|\n|\u2028|\u2029/g, function (match) {return escapeCharacters[match];});
}
function escapeHtmlFunction (html) {
var escapeCharacters = {
"&": "&"
, "<": "<"
, ">": ">"
, "\"": """
, "'": "'"
, "`": "`"
};
return String(html).replace(/(?:&|<|>|"|'|`)/g, function (match) {return escapeCharacters[match];});
}
function block (templatePartString, settingsObject, dataObject) {
return new Template(templatePartString, settingsObject).render(dataObject);
}
return {
Template: Template
, block: block
};
});
var template = '<div><p>Total: <%- value %></p><% var a = 2; while (a--) { %><%- block(innerTemplate, {delimiters: ["{{", "}}"]}, {innerValue: innerValue}) %><% } %></div>'
, innerTemplate = '<p>Last: {{- innerValue }}</p>';
var result = new TPL.Template(template).render({value: '<span>15</span>', block: TPL.block, innerTemplate: innerTemplate, innerValue: '<span>20</span>'});
var fragment = document.createDocumentFragment()
, element = document.createElement('div');
element.innerHTML = result;
fragment.appendChild(element);
document.getElementsByTagName('body')[0].appendChild(fragment);
</script>
</body>
</html>
Комментариев нет:
Отправить комментарий