Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Commit counter 22. Major update, including some BREAKING CHANGES, and…

… many

new features. More samples and documentation for new features will be added
incrementally in coming updates.

Among the changes:

Detailed APIs modified for consistent arguments and use of this
pointer, and for maximum extensibility. See updated samples for usage...

Compiled templates restructured for easier debugging.

View object restructured for clarity.

View now has a type property, e.g. type="item"
Only "item" views have index properties, but to get the index from a nested
view use view.get("item").index.

nodes collection on a view is now a function, view.nodes().

Settings grouped onto a $.views.settings object.
View navigation features improved, with view.get(...) and $.view(elem, ...)
tagCtx object provides improved access to the args and properties of a tag
 invocation.

Adding resources (helpers, converters, tags, etc) to a template now supported
by passing parent template to API. e.g. $.tags({...}, parentTemplate).
Many improvements to custom tags, - used also as part of JsViews integration
for new JsViews Tag Controls. (Instantiation of tags as control instances).

Template inclusion now supported with simpler syntax {{for tmpl=.../))

Fixes for issues #169, #162, #157, #156, #155, #153, #145
  • Loading branch information...
commit 69ce6ce028fdb813ca7c13da0076651dda967b26 1 parent 734d3bd
@BorisMoore authored
Showing with 1,149 additions and 980 deletions.
  1. +2 −2 README.md
  2. +25 −32 demos/demos.html
  3. +4 −4 demos/index.html
  4. +4 −1 demos/resources/demos.css
  5. +4 −4 demos/scenarios/01_default-values-scenario.html
  6. +3 −4 demos/scenarios/02_separators-scenario.html
  7. +4 −4 demos/scenarios/04_assigning-variables-scenario.html
  8. +5 −4 demos/step-by-step/02_compiling-named-templates-from-strings.html
  9. +20 −11 demos/step-by-step/03_converters-and-encoding.html
  10. +5 −1 demos/step-by-step/06_template-composition.html
  11. +4 −4 demos/step-by-step/08_custom-tags.html
  12. +1 −1  demos/step-by-step/11_accessing-parent-data.html
  13. +16 −9 demos/step-by-step/12_passing-in-context.html
  14. +1 −1  demos/step-by-step/13_associating-helpers-with-templates.html
  15. +4 −4 demos/step-by-step/20_without-jquery.html
  16. +5 −4 demos/variants/accessing-templates/01_compiling-template-objects-from-strings.html
  17. +5 −4 demos/variants/accessing-templates/02_registering-named-template-from-script-declaration.html
  18. +5 −4 demos/variants/accessing-templates/03_getting-template-objects-from-script-declaration.html
  19. +2 −2 demos/variants/accessing-templates/04_template-composition-subtemplates.html
  20. +1 −1  demos/variants/accessing-templates/05_template-composition-templateobjects.html
  21. +8 −5 demos/variants/variants.html
  22. +886 −645 jsrender.js
  23. +4 −4 test/perf-compare.html
  24. +68 −68 test/resources/handlebars.js
  25. +1 −1  test/{unit-tests-no-jquery.html → unit-tests-jsrender-no-jquery.html}
  26. +1 −1  test/{unit-tests-with-jquery.html → unit-tests-jsrender-with-jquery.html}
  27. +49 −137 test/{unit/jsrender-tests-no-jquery.js → unit-tests/tests-jsrender-no-jquery.js}
  28. +12 −18 test/{unit/jsrender-tests-with-jquery.js → unit-tests/tests-jsrender-with-jquery.js}
View
4 README.md
@@ -9,5 +9,5 @@ See [Approaching Beta: What's changing in JsRender and JsViews](http://www.boris
See also [JsRender Fundamentals](http://johnpapa.net/new-course-on-jsrender-templating-fundamentals-with-javascript) training course from John Papa on [Pluralsight](http://pluralsight.net)</br>
**Warning:** JsRender is not yet officially beta, though the APIs and code are now stable. JsViews, on the other hand, is still evolving (with a number of
-powerful features arriving), and its Beta is currently planned for late September or early October. Since this could lead to small API changes in JsRender
-(to accomodate JsViews integration) JsRender will not be declared officially Beta until around the same time. Thank you for you patience!<br/>
+powerful features arriving), and its Beta is currently planned for late December or January. Since this could lead to small API changes in JsRender
+(to accomodate JsViews integration), JsRender will not be declared officially Beta until around the same time. Thank you for your patience!<br/>
View
57 demos/demos.html
@@ -10,39 +10,32 @@
<h2>JsRender: Demos</h2>
-<h3>JsRender - step-by-step samples</h3>
-
-<ul class="indexitems">
- <li><a href="step-by-step/01_inserting-data.html">Inserting data values</a></li>
- <li><a href="step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates from strings</a></li>
- <li><a href="step-by-step/03_converters-and-encoding.html">{{: }} and {{> }}</a></li>
- <li><a href="step-by-step/04_if-else-tag.html">{{if}} and {{else}}</a></li>
- <li><a href="step-by-step/05_for-tag.html">{{for}}</a></li>
- <li><a href="step-by-step/06_template-composition.html">Template composition</a></li>
- <li><a href="step-by-step/07_paths.html">Accessing paths</a></li>
- <li><a href="step-by-step/08_custom-tags.html">Custom tags</a></li>
- <li><a href="step-by-step/09_helper-functions.html">'Helper' functions</a></li>
- <li><a href="step-by-step/10_comparison-tests.html">Comparison tests</a></li>
- <li><a href="step-by-step/11_accessing-parent-data.html">Accessing parent data</a></li>
- <li><a href="step-by-step/12_passing-in-context.html">Passing in context</a></li>
- <li><a href="step-by-step/13_associating-helpers-with-templates.html">Associating helpers with templates</a></li>
- <li><a href="step-by-step/20_without-jquery.html">JsRender without jQuery</a></li>
-</ul>
-
-<h3>JsRender - variants and details</h3>
-
-<ul class="indexitems">
- <li><a href="variants/variants.html">Samples: variants and details</a></li>
-</ul>
-
-<h3>JsRender - scenario examples</h3>
-
<ul class="indexitems">
- <li><a href="scenarios/01_default-values-scenario.html">'Default values' scenario</a></li>
- <li><a href="scenarios/02_separators-scenario.html">'Separators' scenario</a></li>
- <li><a href="scenarios/03_iterating-through-fields-scenario.html">'Iterating through fields' scenario</a></li>
- <li><a href="scenarios/04_assigning-variables-scenario.html">'Assigning variables' scenario</a></li>
- <li><a href="scenarios/05_arrays-plus-headers-and-footers.html">Layout templates: headers, footers and rendered items</a></li>
+ <li class="subhead">Step-by-step samples:</li>
+ <li class="inset">- <a href="step-by-step/01_inserting-data.html">Inserting data values</a></li>
+ <li class="inset">- <a href="step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates from strings</a></li>
+ <li class="inset">- <a href="step-by-step/03_converters-and-encoding.html">{{: }} and {{> }}</a></li>
+ <li class="inset">- <a href="step-by-step/04_if-else-tag.html">{{if}} and {{else}}</a></li>
+ <li class="inset">- <a href="step-by-step/05_for-tag.html">{{for}}</a></li>
+ <li class="inset">- <a href="step-by-step/06_template-composition.html">Template composition</a></li>
+ <li class="inset">- <a href="step-by-step/07_paths.html">Accessing paths</a></li>
+ <li class="inset">- <a href="step-by-step/08_custom-tags.html">Custom tags</a></li>
+ <li class="inset">- <a href="step-by-step/09_helper-functions.html">'Helper' functions</a></li>
+ <li class="inset">- <a href="step-by-step/10_comparison-tests.html">Comparison tests</a></li>
+ <li class="inset">- <a href="step-by-step/11_accessing-parent-data.html">Accessing parent data</a></li>
+ <li class="inset">- <a href="step-by-step/12_passing-in-context.html">Passing in context</a></li>
+ <li class="inset">- <a href="step-by-step/13_associating-helpers-with-templates.html">Associating helpers with templates</a></li>
+ <li class="inset">- <a href="step-by-step/20_without-jquery.html">JsRender without jQuery</a></li>
+
+ <li class="subhead">Variants and details:</li>
+ <li class="inset">- <a href="variants/variants.html">Samples: variants and details</a></li>
+
+ <li class="subhead">Scenario examples:</li>
+ <li class="inset">- <a href="scenarios/01_default-values-scenario.html">'Default values' scenario</a></li>
+ <li class="inset">- <a href="scenarios/02_separators-scenario.html">'Separators' scenario</a></li>
+ <li class="inset">- <a href="scenarios/03_iterating-through-fields-scenario.html">'Iterating through fields' scenario</a></li>
+ <li class="inset">- <a href="scenarios/04_assigning-variables-scenario.html">'Assigning variables' scenario</a></li>
+ <li class="inset">- <a href="scenarios/05_arrays-plus-headers-and-footers.html">Layout templates: headers, footers and rendered items</a></li>
</ul>
</body>
</html>
View
8 demos/index.html
@@ -13,15 +13,15 @@
<div class="box">
<div class="desc">JsRender templates are optimized for high-performance pure string-based rendering, without DOM or jQuery dependency</div>
<div class="subhead"><b><a href="demos.html">JsRender: Demos</a></b></div>
- <div class="label">Source code:</div>
+ <div class="label">Source code:</div>
<div><a href="https://github.com/BorisMoore/jsrender">https://github.com/BorisMoore/jsrender</a></div>
</div>
<div class="subhead"><em>Tests</em>:</div>
<div class="box">
- <div class="subhead"><b><a href="../test/unit-tests-with-jquery.html">JsRender unit tests - with jQuery</a></b></div>
- <div class="subhead"><b><a href="../test/unit-tests-no-jquery.html">JsRender unit tests - without jQuery</a></b></div>
+ <div class="subhead"><b><a href="../test/unit-tests-jsrender-with-jquery.html">JsRender unit tests - with jQuery</a></b></div>
+ <div class="subhead"><b><a href="../test/unit-tests-jsrender-no-jquery.html">JsRender unit tests - without jQuery</a></b></div>
<div><a href="../test/perf-compare.html">Perf comparison</a></div>
</div>
@@ -30,7 +30,7 @@
<div class="box">
<div class="desc">JsViews are interactive data-driven views, built on top of JsRender templates</div>
<div class="subhead"><b><a href="http://borismoore.github.com/jsviews/demos/index.html">JsViews: Demos</a></b></div>
- <div class="label">JsViews and JsRender Overview:</div>
+ <div class="label">JsViews and JsRender Overview:</div>
<div class="subhead"><b><a href="http://borismoore.github.com/jsviews/demos/jQueryConfDemosOct2011/index.html" >Demo sequence from jQuery Conference October 2011</a></b></div>
</div>
View
5 demos/resources/demos.css
@@ -7,11 +7,14 @@ body > button { float: left; clear: right; margin: 3px }
a { color: #55b; }
pre { font-size:10pt; font-weight:bold; }
.inset { padding-left: 18px; }
-.box { border: 1px solid #777; padding: 5px; margin: 5px 0 30px; }
+.box { border: 1px solid #777; padding: 10px; margin: 5px 0 30px; }
.box div { margin: 3px 0 10px 0; }
.box .label { margin: 0; padding: 10px 0 0 0; font-style:italic; color: #55b; }
.box.label { font-style:italic; color: #55b; }
.desc { font-style:italic; margin: 0 0 15px; color:#116; }
pre { border-left: 3px solid #aaa; padding:10px; margin-bottom: 30px; }
.indexitems { list-style-type:none; padding-left:10px; margin: 0 0 20px;}
+.indexitems li { margin-top:14px;}
+.indexitems .inset { margin-top:6px;}
h3 { margin-bottom: 10px; font-size: 11pt;}
+select { margin-bottom:15px; width: 200px; }
View
8 demos/scenarios/01_default-values-scenario.html
@@ -37,7 +37,7 @@
$.views.tags({
get: function( value ) {
- return value || this.props.defaultValue;
+ return value || this.ctx.props.defaultValue;
}
});
</pre>
@@ -56,7 +56,7 @@
$.views.tags({
yesNo: function( value ) {
- return value ? this.props.yes : this.props.no;
+ return value ? this.tagCtx.props.yes : this.tagCtx.props.no;
}
});
</pre>
@@ -104,11 +104,11 @@
$.views.tags({
get: function( value ) {
- return value || this.props.defaultValue;
+ return value || this.tagCtx.props.defaultValue;
},
yesNo: function( value ) {
- return value ? this.props.yes : this.props.no;
+ return value ? this.tagCtx.props.yes : this.tagCtx.props.no;
}
});
View
7 demos/scenarios/02_separators-scenario.html
@@ -2,6 +2,7 @@
<html>
<head>
<script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
+ <script src="../../jquery-1.8.0.js" type="text/javascript"></script>
<script src="../../jsrender.js" type="text/javascript"></script>
<link href="../resources/demos.css" rel="stylesheet" type="text/css" />
@@ -169,13 +170,11 @@
$.views.helpers({
nextToLast: function() {
- var view = this;
- return view.index === view.parent.data.length - 2;
+ return this.index === this.parent.data.length - 2;
},
notLast: function() {
- var view = this;
- return view.index !== view.parent.data.length - 1;
+ return this.index !== this.parent.data.length - 1;
}
});
View
8 demos/scenarios/04_assigning-variables-scenario.html
@@ -61,14 +61,14 @@
<td>
{{if languages}}
{{setvar "summary" languages/}}
-
+
Alternative languages: <em>{{>languages}}</em>.
{{else}}
{{setvar "summary"}}
<b>Subtitles only:</b> {{>subtitles}}
{{/setvar}}
-
- Subtitles only. See summary column:
+
+ Subtitles only. See summary column:
{{/if}}
</td>
<td>
@@ -108,7 +108,7 @@
if (value) {
vars[key] = value;
} else {
- vars[key] = this.renderContent(this.view);
+ vars[key] = this.renderContent(this.tagCtx.view);
}
}
});
View
9 demos/step-by-step/02_compiling-named-templates-from-strings.html
@@ -2,7 +2,7 @@
<html>
<head>
<script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
- <script src="../../jsrender.js" type="text/javascript"></script>
+ <script src="../../jsrender21.js" type="text/javascript"></script>
<link href="../resources/demos.css" rel="stylesheet" type="text/css" />
<link href="../resources/movielist.css" rel="stylesheet" type="text/css" />
@@ -34,16 +34,17 @@
var details = true;
function switchTemplates() {
- var html;
+ var html,
+ button = $("#switchBtn");
details = !details;
/* Render using the other named template */
if ( details ) {
- $( this ).text( "Show titles only" );
+ button.text( "Show titles only" );
html = $.render.detailTemplate( movies );
} else {
- $( this ).text( "Show full details" );
+ button.text( "Show full details" );
html = $.render.titleTemplate( movies );
}
$( "#movieList" ).html( html );
View
31 demos/step-by-step/03_converters-and-encoding.html
@@ -19,7 +19,7 @@
<ul>
<li>{{:value}} does not convert. Used to render values that include html markup</li>
-<li>{{loc:value}} Uses custom converter.</li>
+<li>{{loc:value lang="..."}} Uses custom converter.</li>
<li>{{html:value}} Converts using built-in HTML encoder. (Better security, but slight perf cost)</li>
<li>{{>value}} Alternative syntax for built-in HTML encoder.</li>
</ul><br />
@@ -30,14 +30,15 @@
<script id="movieTemplate" type="text/x-jsrender">
<tr>
- <td>{{loc:title}}</td>
+ <td>{{loc:title lang='EN'}}</td>
+ <td>{{loc:title lang='FR'}}</td>
<td class="synopsis">{{:synopsis}}</td>
<td class="synopsis">{{>synopsis}}</td>
</tr>
</script>
<table>
- <thead><tr><th>Title (loc:French)</th><th>No Convert</th><th>HTML Encode</th></tr></thead>
+ <thead><tr><th>Title (loc:English)</th><th>Title (loc:French)</th><th>No Convert</th><th>HTML Encode</th></tr></thead>
<tbody id="movieList"></tbody>
</table>
@@ -56,18 +57,26 @@
$.views.converters({
loc: function (value) {
- switch (value) {
- case "Meet Joe Black":
- return "Rencontrez Joe Black";
+ var result = "";
+
+ switch(this.tagCtx.props.lang) {
+ case "EN":
+ result = value;
break;
- case "Eyes Wide Shut":
- return "Les Yeux Grand Fermés";
- break;
+ case "FR":
+ switch (value) {
+ case "Meet Joe Black":
+ result = "Rencontrez Joe Black";
+ break;
- default:
- return value||"";
+ case "Eyes Wide Shut":
+ result = "Les Yeux Grand Fermés";
+ break;
+ }
+ break;
}
+ return result;
}
});
$( "#movieList" ).html(
View
6 demos/step-by-step/06_template-composition.html
@@ -14,7 +14,7 @@
<script id="movieTemplate" type="text/x-jsrender">
<tr>
- <td>{{>title}}</td>
+ {{for tmpl="#headerTemplate"/}}
<td>
{{for languages tmpl="#columnTemplate"/}}
</td>
@@ -27,6 +27,10 @@
</tr>
</script>
+<script id="headerTemplate" type="text/x-jsrender">
+ <td>{{>title}}</td>
+</script>
+
<script id="columnTemplate" type="text/x-jsrender">
<div>
<em>{{>name}}</em>
View
8 demos/step-by-step/08_custom-tags.html
@@ -19,9 +19,9 @@
// Tag to reverse-sort an array
- sort: function( array ) {
+ sort: function( array ){
var ret = "";
- if ( this.props.reverse ) {
+ if ( this.tagCtx.props.reverse ) {
// Render in reverse order
for ( var i = array.length; i; i-- ) {
ret += this.renderContent( array[ i - 1 ] );
@@ -67,9 +67,9 @@
$.views.tags({
// Tag to reverse-sort an array
- sort: function( array ) {
+ sort: function( array ){
var ret = "";
- if ( this.props.reverse ) {
+ if ( this.tagCtx.props.reverse ) {
// Render in reverse order
for ( var i = array.length; i; i-- ) {
ret += this.renderContent( array[ i - 1 ] );
View
2  demos/step-by-step/11_accessing-parent-data.html
@@ -89,7 +89,7 @@
var model = {
specialMessage: function(language, title) {
- if (language === "French" && title === "City Hunter") { return ": (temporarily unavailable)"; }
+ if (language === "French" && title === "City Hunter") { return ": (special offer)"; }
},
theater: "Rialto",
View
25 demos/step-by-step/12_passing-in-context.html
@@ -16,8 +16,10 @@
<pre>
$( selector ).render( data, {
reverseSort: reverse,
- buttonCaption: reverse ? "Sort increasing" : "Sort decreasing",
- format: myFormatFunction
+ format: myFormatFunction,
+ buttonCaption: function(val) {
+ ...
+ }
})
</pre>
@@ -25,7 +27,7 @@
<div class="subhead">registered globally as helpers, or registered as helpers for a specific template.</div>
<pre>
-&lt;th>&lt;button>{{>~buttonCaption}}&lt;/button>&lt;/th>
+&lt;th>&lt;button>{{>~buttonCaption('sort')}}&lt;/button>&lt;/th>
...
&lt;td>{{>~format(title)}}&lt;/td>
...
@@ -37,8 +39,8 @@
<script id="movieTemplate" type="text/x-jsrender">
<thead>
<tr>
- <th><button id="formatBtn">{{>~format('Title')}}</button></th>
- <th><button id="sortBtn">{{>~buttonCaption}}</button></th>
+ <th>Title <button id="formatBtn">{{>~buttonCaption('case')}}</button></th>
+ <th><button id="sortBtn">{{>~buttonCaption('sort')}}</button></th>
</tr>
</thead>
<tbody>
@@ -65,9 +67,9 @@
$.views.tags({
// Tag to reverse-sort an array
- sort: function( array ) {
+ sort: function( array ){
var ret = "";
- if ( this.props.reverse ) {
+ if ( this.tagCtx.props.reverse ) {
// Render in reverse order
for ( var i = array.length; i; i-- ) {
ret += this.renderContent( array[ i - 1 ] );
@@ -119,8 +121,13 @@
$( "#movieList" ).html(
$( "#movieTemplate" ).render( [movies], {
reverseSort: reverse,
- buttonCaption: reverse ? "Sort increasing" : "Sort decreasing",
- format: myFormatFunction
+ format: myFormatFunction,
+ buttonCaption: function(val) {
+ if (val === 'sort') {
+ return reverse ? "Sort increasing" : "Sort decreasing";
+ }
+ return upperCase ? "to lower" : "to upper";
+ }
})
);
}
View
2  demos/step-by-step/13_associating-helpers-with-templates.html
@@ -24,7 +24,7 @@
});
</pre>
-<div class="subhead">Passing different helpers to a subtemplate based on the context where it is used.</div>
+<div class="subhead">Passing different helpers to a sub-template based on the context where it is used.</div>
<pre>
{{for suppliers tmpl="personTmpl" ~utils=~supplierUtils/}}
</pre>
View
8 demos/step-by-step/20_without-jquery.html
@@ -43,16 +43,16 @@
jsviews.tags({
- sort: function( array ) {
+ sort: function( array ){
var ret = "";
- if ( this.props.reverse ) {
+ if ( this.tagCtx.props.reverse ) {
// Render in reverse order
for ( var i = array.length; i; i-- ) {
- ret += this.tmpl.render( array[ i - 1 ] );
+ ret += this.renderContent( array[ i - 1 ] );
}
} else {
// Render in original order
- ret += this.tmpl.render( array );
+ ret += this.renderContent( array );
}
return ret;
}
View
9 demos/variants/accessing-templates/01_compiling-template-objects-from-strings.html
@@ -12,7 +12,7 @@
<h3>Compiling template objects from strings</h3>
-<div class="subhead"> Variant of <a href="../../step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates sample</a></div><br />
+<div class="subhead"> Variant of '<a href="../../step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates</a>' sample</div><br />
<button id="switchBtn">Show full details</button><br/>
<br />
@@ -33,16 +33,17 @@
details = true;
function switchTemplates() {
- var html;
+ var html,
+ button = $("#switchBtn");
details = !details;
/* Render using the other compiled template */
if ( details ) {
- $( this ).text( "Show titles only" );
+ button.text( "Show titles only" );
html = detailTemplate.render( movies );
} else {
- $( this ).text( "Show full details" );
+ button.text( "Show full details" );
html = titleTemplate.render( movies );
}
$( "#movieList" ).html( html );
View
9 demos/variants/accessing-templates/02_registering-named-template-from-script-declaration.html
@@ -12,7 +12,7 @@
<h3>Register script block template declarations, as named templates</h3>
-<div class="subhead"> Variant of <a href="../../step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates sample</a></div><br />
+<div class="subhead"> Variant of '<a href="../../step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates</a>' sample</div><br />
<script id="titleTemplate" type="text/x-jsrender">
<tr>
@@ -50,16 +50,17 @@
var details = true;
function switchTemplates() {
- var html;
+ var html,
+ button = $("#switchBtn");
details = !details;
/* Render using the other compiled template */
if ( details ) {
- $( this ).text( "Show titles only" );
+ button.text( "Show titles only" );
html = $.render.detailTemplate( movies );
} else {
- $( this ).text( "Show full details" );
+ button.text( "Show full details" );
html = $.render.titleTemplate( movies );
}
$( "#movieList" ).html( html );
View
9 demos/variants/accessing-templates/03_getting-template-objects-from-script-declaration.html
@@ -12,7 +12,7 @@
<h3>Getting template objects from script block template declarations</h3>
-<div class="subhead"> Variant of <a href="../../step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates sample</a></div><br />
+<div class="subhead"> Variant of '<a href="../../step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates</a>' sample</div><br />
<script id="titleTemplate" type="text/x-jsrender">
<tr>
@@ -48,16 +48,17 @@
details = true;
function switchTemplates() {
- var html;
+ var html,
+ button = $("#switchBtn");
details = !details;
/* Render using the other compiled template */
if ( details ) {
- $( this ).text( "Show titles only" );
+ button.text( "Show titles only" );
html = detailTemplate.render( movies );
} else {
- $( this ).text( "Show full details" );
+ button.text( "Show full details" );
html = titleTemplate.render( movies );
}
$( "#movieList" ).html( html );
View
4 demos/variants/accessing-templates/04_template-composition-subtemplates.html
@@ -10,9 +10,9 @@
<body>
<div class="subhead"><< <a href="../variants.html">JsRender Demos: Variants</a></div>
-<h3>Template composition. Registering and accessing subtemplates.</h3>
+<h3>Template composition. Registering and accessing sub-templates.</h3>
-<div class="subhead"> Variant of <a href="../../step-by-step/06_template-composition.html">template composition sample</a></div><br />
+<div class="subhead"> Variant of '<a href="../../step-by-step/06_template-composition.html">Template composition</a>' sample</div><br />
<script id="movieTemplate" type="text/x-jsrender">
<tr>
View
2  demos/variants/accessing-templates/05_template-composition-templateobjects.html
@@ -12,7 +12,7 @@
<h3>Template composition. Passing in template objects as the contextual template parameters.</h3>
-<div class="subhead"> Variant of <a href="../../step-by-step/06_template-composition.html">template composition sample</a></div><br />
+<div class="subhead"> Variant of '<a href="../../step-by-step/06_template-composition.html">Template composition</a>' sample</div><br />
<script id="movieTemplate" type="text/x-jsrender">
<tr>
View
13 demos/variants/variants.html
@@ -13,11 +13,14 @@
<h3>Accessing templates</h3>
<ul class="indexitems">
- <li><a href="accessing-templates/01_compiling-template-objects-from-strings.html">Compiling template objects from strings</a></li>
- <li><a href="accessing-templates/02_registering-named-template-from-script-declaration.html">Registering script block template declarations as named templates</a></li>
- <li><a href="accessing-templates/03_getting-template-objects-from-script-declaration.html">Getting template objects from script declarations</a></li>
- <li><a href="accessing-templates/04_template-composition-subtemplates.html">Template composition: Registering subtemplates</a></li>
- <li><a href="accessing-templates/05_template-composition-templateobjects.html">Template composition: Accessing template objects from context</a></li>
+ <li class="subhead">Variants of '<a href="../step-by-step/02_compiling-named-templates-from-strings.html">Compiling named templates</a>' sample:</li>
+ <li class="inset">- <a href="accessing-templates/01_compiling-template-objects-from-strings.html">Compiling template objects from strings</a></li>
+ <li class="inset">- <a href="accessing-templates/02_registering-named-template-from-script-declaration.html">Registering script block template declarations as named templates</a></li>
+ <li class="inset">- <a href="accessing-templates/03_getting-template-objects-from-script-declaration.html">Getting template objects from script declarations</a></li>
+
+ <li class="subhead">Variants of '<a href="../step-by-step/06_template-composition.html">Template composition</a>' sample:</li>
+ <li class="inset">- <a href="accessing-templates/04_template-composition-subtemplates.html">Template composition: Registering sub-templates</a></li>
+ <li class="inset">- <a href="accessing-templates/05_template-composition-templateobjects.html">Template composition: Accessing template objects from context</a></li>
</ul>
</body>
View
1,531 jsrender.js
@@ -6,75 +6,121 @@
* Copyright 2012, Boris Moore
* Released under the MIT License.
*/
-// informal pre beta commit counter: 21
+// informal pre beta commit counter: 22
(function(global, jQuery, undefined) {
// global is the this object, which is window when running in the usual browser environment.
+ "use strict";
- if (jQuery && jQuery.views || global.jsviews) return; // JsRender is already loaded
+ if (jQuery && jQuery.views || global.jsviews) { return; } // JsRender is already loaded
//========================== Top-level vars ==========================
var versionNumber = "v1.0pre",
- $, rTag, rTmplString, $extend,
-// compiledTmplsCache = {},
- delimOpenChar0 = "{", delimOpenChar1 = "{", delimCloseChar0 = "}", delimCloseChar1 = "}", deferChar = "!",
- $viewsSub = {},
+ $, jsvStoreName, rTag, rTmplString,
+//TODO tmplFnsCache = {},
+ delimOpenChar0 = "{", delimOpenChar1 = "{", delimCloseChar0 = "}", delimCloseChar1 = "}", linkChar = "^",
FALSE = false, TRUE = true,
- rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,
- // nil object helper view viewProperty pathTokens leafToken string
+ rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g,
+ // object helper view viewProperty pathTokens leafToken
- rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,
- // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space
+ rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,
+ // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space
// (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space
rNewLine = /\r?\n/g,
rUnescapeQuotes = /\\(['"])/g,
- rEscapeQuotes = /\\?(['"])/g,
+ // escape quotes and \ character
+ rEscapeQuotes = /([\\'"])/g,
rBuildHash = /\x08(~)?([^\x08]+)\x08/g,
-
+ rTestElseIf = /^if\s/,
+ rFirstElem = /<(\w+)[>\s]/,
+ rPrevElem = /<(\w+)[^>\/]*>[^>]*$/,
autoTmplName = 0,
+ viewId = 0,
escapeMapForHtml = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;"
},
+ attrEncodeChars = /[<"'&]/g,
+ htmlEncodeChars = /[\x00<>"'&]/g,
tmplAttr = "data-jsv-tmpl",
fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,",
- htmlSpecialChar = /[\x00"&'<>]/g,
- slice = Array.prototype.slice,
+ slice = [].slice,
$render = {},
+ jsvStores = {
+ template: {
+ compile: compileTmpl
+ },
+ tag: {
+ compile: compileTag
+ },
+ helper: {},
+ converter: {}
+ },
// jsviews object ($.views if jQuery is loaded)
$views = {
jsviews: versionNumber,
- sub: $viewsSub, // subscription, e.g. JsViews integration
- debugMode: TRUE,
render: $render,
- templates: $templates,
- tags: $viewsTags,
- helpers: $viewsHelpers,
- converters: $viewsConverters,
- delimiters: $viewsDelimiters,
View: View,
- _convert: convert,
- _err: function(e) {
- return $views.debugMode ? ("Error: " + (e.message || e)) + ". " : '';
+ settings: {
+ delimiters: $viewsDelimiters,
+ debugMode: TRUE
+ },
+ sub: {
+ // subscription, e.g. JsViews integration
+ Error: JsViewsError,
+ tmplFn: tmplFn,
+ parse: parseParams,
+ extend: $extend,
+ error: error
+//TODO invoke: $invoke
},
- _tmplFn: tmplFn,
+ _cnvt: convertVal,
_tag: renderTag,
- error: error,
- Error: JsViewsError
+
+ // TODO provide better debug experience - e.g. support $.views.onError callback
+ _err: function(e) {
+ // Place a breakpoint here to intercept template rendering errors
+ return $viewsSettings.debugMode ? ("Error: " + (e.message || e)) + ". " : '';
+ }
};
- function JsViewsError(message) { // Error exception type for JsViews/JsRender
- this.name = "JsRender Error",
- this.message = message || "JsRender error"
+ function JsViewsError(message, object) {
+ // Error exception type for JsViews/JsRender
+ // Override of $.views.sub.Error is possible
+ if (object && object.onError) {
+ if (object.onError(message) === FALSE) {
+ return;
+ }
+ }
+ this.name = "JsRender Error";
+ this.message = message || "JsRender error";
+ }
+
+ function $extend(target, source) {
+ var name;
+ target = target || {};
+ for (name in source) {
+ target[name] = source[name];
+ }
+ return target;
}
+//TODO function $invoke() {
+// try {
+// return arguments[1].apply(arguments[0], arguments[2]);
+// }
+// catch(e) {
+// throw new $views.sub.Error(e, arguments[0]);
+// }
+// }
+
(JsViewsError.prototype = new Error()).constructor = JsViewsError;
//========================== Top-level functions ==========================
@@ -83,312 +129,619 @@
// jsviews.delimiters
//===================
- function $viewsDelimiters(openChars, closeChars, defer) {
- // Set the tag opening and closing delimiters. Default is "{{" and "}}"
- // openChar, closeChars: opening and closing strings, each with two characters
+ function $viewsDelimiters(openChars, closeChars, link) {
+ // Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^"
+ // openChars, closeChars: opening and closing strings, each with two characters
if (!$views.rTag || arguments.length) {
- delimOpenChar0 = openChars ? "\\" + openChars.charAt(0) : delimOpenChar0; // Escape the characters - since they could be regex special characters
- delimOpenChar1 = openChars ? "\\" + openChars.charAt(1) : delimOpenChar1;
- delimCloseChar0 = closeChars ? "\\" + closeChars.charAt(0) : delimCloseChar0;
- delimCloseChar1 = closeChars ? "\\" + closeChars.charAt(0) : delimCloseChar1;
- defer = defer ? "\\" + defer : deferChar;
-
+ delimOpenChar0 = openChars ? openChars.charAt(0) : delimOpenChar0; // Escape the characters - since they could be regex special characters
+ delimOpenChar1 = openChars ? openChars.charAt(1) : delimOpenChar1;
+ delimCloseChar0 = closeChars ? closeChars.charAt(0) : delimCloseChar0;
+ delimCloseChar1 = closeChars ? closeChars.charAt(1) : delimCloseChar1;
+ linkChar = link || linkChar;
+ openChars = "\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1; // Default is "{^{"
+ closeChars = "\\" + delimCloseChar0 + "\\" + delimCloseChar1; // Default is "}}"
// Build regex with new delimiters
- $views.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions
- // tag (followed by / space or }) or cvtr+colon or html or code
- = "(\\w*" + defer + ")?(?:(?:(\\w+(?=[\\/\\s" + delimCloseChar0 + "]))|(?:(\\w+)?(:)|(>)|(\\*)))"
- // params
- + "\\s*((?:[^" + delimCloseChar0 + "]|" + delimCloseChar0 + "(?!" + delimCloseChar1 + "))*?)";
+ // tag (followed by / space or }) or cvtr+colon or html or code
+ rTag = "(?:(?:(\\w+(?=[\\/\\s\\" + delimCloseChar0 + "]))|(?:(\\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\\*)))"
+ + "\\s*((?:[^\\" + delimCloseChar0 + "]|\\" + delimCloseChar0 + "(?!\\" + delimCloseChar1 + "))*?)";
+
+ // make rTag available to JsViews (or other components) for parsing binding expressions
+ $views.rTag = rTag + ")";
- // slash or closeBlock }}
- rTag = new RegExp(delimOpenChar0 + delimOpenChar1 + rTag + "(\\/)?|(?:\\/(\\w+)))" + delimCloseChar0 + delimCloseChar1, "g");
+ rTag = new RegExp(openChars + rTag + "(\\/)?|(?:\\/(\\w+)))" + closeChars, "g");
- // Default rTag: tag converter colon html code params slash closeBlock
- // /{{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}
+ // Default: bind tag converter colon html comment code params slash closeBlock
+ // /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g
- rTmplString = new RegExp("<.*>|([^\\\\]|^)[{}]|" + delimOpenChar0 + delimOpenChar1 + ".*" + delimCloseChar0 + delimCloseChar1);
- // rTmplString looks for html tags or { or } char not preceeded by \\, or JsRender tags {{xxx}}. Each of these strings are considered NOT to be jQuery selectors
+ rTmplString = new RegExp("<.*>|([^\\\\]|^)[{}]|" + openChars + ".*" + closeChars);
+ // rTmplString looks for html tags or { or } char not preceded by \\, or JsRender tags {{xxx}}. Each of these strings are considered NOT to be jQuery selectors
}
- return [delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, deferChar];
+ return [delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, linkChar];
}
- //=================
+ //=========
+ // View.get
+ //=========
+
+ function getView(type) {
+ // TODO complete/test/provide samples for this
+ // If type is undefined, returns root view (view under top view).
+ var view = this,
+ root = !type || type === "root";
+ while (root && view.parent.parent || view && view.type !== type) {
+ view = view.parent;
+ }
+ return view;
+ }
+
+ //==========
// View._hlp
- //=================
+ //==========
function getHelper(helper) {
- // Helper method called as view._hlp() from compiled template, for helper functions or template parameters ~foo
- var view = this,
+ // Helper method called as view._hlp(key) from compiled template, for helper functions or template parameters ~foo
+ var wrapped,
+ view = this,
+ viewCtx = view.ctx ||{},
tmplHelpers = view.tmpl.helpers || {};
helper = (
- view.dynCtx && view.dynCtx[helper] !== undefined
- ? view.dynCtx
- : view.ctx[helper] !== undefined
- ? view.ctx
- : tmplHelpers[helper] !== undefined
- ? tmplHelpers
- : $viewsHelpers[helper] !== undefined
- ? $viewsHelpers
- : {}
+ viewCtx[helper] !== undefined
+ ? viewCtx
+ : tmplHelpers[helper] !== undefined
+ ? tmplHelpers
+ : $helpers[helper] !== undefined
+ ? $helpers
+ : {}
)[helper];
- return typeof helper !== "function" ? helper : function() {
- return helper.apply(view, arguments);
- };
- }
- //=================
- // jsviews._convert
- //=================
+ if (helper) {
+ if (typeof helper === "function") {
+ wrapped = function() {
+ // If it is of type function, we will wrap it so it gets called with view as 'this' context.
+ // If the helper ~foo() was in a data-link expression, the view will have a 'temporary' linkCtx property too.
+ // However note that helper functions on deeper paths will not have access to view and tagCtx.
+ // For example, ~util.foo() will have the ~util object as 'this' pointer
+ var i,
+ args = arguments;
+
+ for (i in args) {
+ if (typeof args[i] === "function") {
+ args[i] = args[i].call(view.data);
+ }
+ }
+ return helper.apply(view, args);
+ };
+ wrapped.depends = helper.depends;
+ }
+ }
+ return wrapped || helper;
+ }
- function convert(converter, view, self, text) {
- // self is template object or link object
- var linkContext = !self.markup && self || undefined,
- tmplConverter = view.tmpl.converters;
- tmplConverter = tmplConverter && tmplConverter[converter] || $viewsConverters[converter];
- return tmplConverter ? tmplConverter.call(view, text, linkContext) : (error("Unknown converter: {{"+ converter + ":"), text);
+ //==============
+ // jsviews._cnvt
+ //==============
+
+ function convertVal(converter, view, self, tagCtx, bindingPaths, text) {
+ // self is template object or linkCtx object
+ if (converter || bindingPaths) {
+ var tmplConverter,
+ linkCtx = !self.markup && self,
+ tag = {
+ tagName: converter + ":",
+ tagCtx: tagCtx
+ },
+ args = tagCtx.args = slice.call(arguments, 5);
+
+ tagCtx.view = view;
+ tagCtx.bind = !!(linkCtx || bindingPaths);
+
+ if (linkCtx) {
+ linkCtx.tag = tag;
+ tag.linkCtx = linkCtx;
+ tagCtx.ctx = extendCtx(tagCtx.ctx, linkCtx.view.ctx);
+ }
+ tag.ctx = tagCtx.ctx || {};
+ delete tagCtx.ctx;
+
+ if (converter) {
+ // A call to {{cnvt: ... }} or {^{cnvt: ... }} or data-link="{cnvt: ... }"
+ tmplConverter = view.tmpl.converters;
+ tmplConverter = tmplConverter && tmplConverter[converter] || $converters[converter];
+ if (tmplConverter || error("Unknown converter: {{"+ converter + ":")) {
+ text = tmplConverter.apply(tag, args);
+ }
+ }
+ if (bindingPaths) {
+ // A call to {^{: ... }} or {^{cnvt: ... }}
+ bindingPaths = view.tmpl.bnds[bindingPaths-1];
+ linkCtx.paths = bindingPaths;
+ // Consider being able to switch off binding if parent view is not currently bound.
+ view._.tag = tag; // Provide this tag on view, for markerNode on bound tags, and for getting the tagCtx and linkCtx during rendering.
+ // Provide this tag on view, for addMarkerNode on bound tags to add the tag to view._.bnds, associated with the tag id,
+ // and so when rendering subsequent {{else}}, will be associated with this tag
+ //TODO does this work with nested elses and with {^{foo:...}} which also adds tag to view, for markerNodes.
+ text = view._.onRender(text, view, TRUE);
+ //Example: text = '<script type="jsv123"></script>' + text + '<script type="jsv123/"></script>';
+ }
+ }
+ return text;
}
- //=================
+ //=============
// jsviews._tag
- //=================
+ //=============
- function renderTag(tag, parentView, self, content, tagInstance) {
- // Called from within compiled template function, to render a nested tag
+ function renderTag(tagName, parentView, self, content, tagCtx, bind) {
+ // Called from within compiled template function, to render a template tag
// Returns the rendered tag
- var ret,
- linkCtx = !self.markup && self, // self is either a template object (if rendering a tag) or a linkCtx object (if linking using a link tag)
- parentTmpl = linkCtx ? linkCtx.view.tmpl : self,
+
+ var ret, render, ctx, elses, tag, tags,
+ tmpl = self.markup && self,
+ // self is either a template object (if rendering a tag) or a linkCtx object (if linking using a link tag)
+ linkCtx = !tmpl && self,
+ parentView_ = parentView._,
+ parentTmpl = tmpl || parentView.tmpl,
tmplTags = parentTmpl.tags,
- nestedTemplates = parentTmpl.templates,
- props = tagInstance.props = tagInstance.props || {},
- tmpl = props.tmpl,
- args = arguments.length > 5 ? slice.call(arguments, 5) : [],
- tagObject = tmplTags && tmplTags[tag] || $viewsTags[tag];
-
- if (!tagObject) {
- error("Unknown tag: {{"+ tag + "}}");
+ childTemplates = parentTmpl.templates,
+ tagDef = tmplTags && tmplTags[tagName] || $tags[tagName],
+ args = tagCtx.args = arguments.length > 6 ? slice.call(arguments, 6) : [],
+ props = tagCtx.props || {};
+
+ tagCtx.view = parentView;
+ tagCtx.ctx = extendCtx(tagCtx.ctx, parentView.ctx); // Extend parentView.ctx
+ ctx = tagCtx.ctx || {};
+ delete tagCtx.ctx;
+
+ if (!tagDef) {
+ error("Unknown tag: {{"+ tagName + "}}");
return "";
}
+ tmpl = props.tmpl;
+
// Set the tmpl property to the content of the block tag, unless set as an override property on the tag
content = content && parentTmpl.tmpls[content - 1];
- tmpl = tmpl || content || tagObject.template || undefined;
- tagInstance.view = parentView;
- tmpl = tagInstance.tmpl =
- "" + tmpl === tmpl // if a string
- ? nestedTemplates && nestedTemplates[tmpl] || $templates[tmpl] || $templates(tmpl)
- : tmpl;
-
- tagInstance.attr =
- // Setting attr on tagInstance so renderContent knows whether to include template annotations.
- self.attr =
- // Setting attr on self.fn to ensure outputting to the correct target attribute.
- self.attr || tagObject.attr;
-
- tagInstance.tagName = tag;
- tagInstance.renderContent = renderContent;
- if (linkCtx) {
- linkCtx.tagCtx = {
- args: args,
- props: props,
- path: tagInstance.path,
- tag: tagObject
+ tmpl = tmpl || content || tagDef.template || undefined;
+ tmpl = "" + tmpl === tmpl // if a string
+ ? childTemplates && childTemplates[tmpl] || $templates[tmpl] || $templates(tmpl)
+ : tmpl;
+
+ if (tagName === "else") {
+ tag = parentView._.tag;
+ // Switch current tagCtx of tag instance to this {{else ...}}
+ elses = tag._elses = tag._elses || [];
+ elses.push(tmpl);
+ tagCtx.isElse = elses.length;
+ render = tag.render;
+ }
+ if (tagDef.init) {
+ // init is the constructor for the tag/control instance
+
+ // tags hash: tag.ctx.tags, merged with parentView.ctx.tags,
+ tags = ctx.tags = parentView.ctx && extendCtx(ctx.tags, parentView.ctx.tags) || {};
+
+ tag = tag || linkCtx.tag;
+ if (tag) {
+ // tag has already been instantiated, so keep it, but attach the current context, which may have changed
+ // Add tag to tags hash
+ tags[tagName] = tag;
+ } else {
+ // If the tag has not already been instantiated, we will create a new instance and add to the tags hash,
+ // so ~tags.tagName will access the tag, even within the rendering of the template content of this tag
+// TODO provide error handling owned by the tag - using tag.onError
+// try {
+ tag = tags[tagName] = new tagDef.init(tagCtx, linkCtx, ctx);
+// }
+// catch(e) {
+// tagDef.onError(e);
+// }
+ tag.tmpl = tmpl;
+
+ if (linkCtx) {
+ tag.attr =
+ // Setting attr on tag so renderContent knows whether to include script node markers.
+ linkCtx.attr =
+ // Setting attr on self to ensure outputting to the correct target attribute.
+ linkCtx.attr || tagDef.attr || "";
+ }
+ }
+ ctx.tag = tag;
+ } else {
+ // This is a simple tag declared as a function. We won't instantiate a specific tag constructor - just a standard instance object.
+ tag = tag || {
+ // tag instance object if no init constructor
+ render: tagDef.render,
+ renderContent: renderContent,
+ tmpl: tmpl,
+ tagName: tagName
};
}
- // If render function is declared, call it. If the return result is undefined, return "", or, if a template (or content) is provide, return the rendered template (using the first parameter as data);
- if (tagObject.render) {
- ret = tagObject.render.apply(tagInstance, args);
+
+ // Provide tagCtx, linkCtx and ctx access from tag
+ tag.tagCtx = tagCtx;
+ tag.ctx = ctx;
+ if (linkCtx) {
+ linkCtx.tag = tag;
+ tag.linkCtx = linkCtx;
}
- return ret || (ret == undefined
- ? (tmpl
- ? tagInstance.renderContent(args[0], undefined, parentView)
- : "")
- : ret.toString()); // (If ret is the value 0 or false, will render to string)
+
+ tag._is = "tag";
+ tag._done = tagCtx.isElse ? tag._done : FALSE; // If not an {{else}} this is a new
+ tmpl = tmpl || tag.tmpl;
+ elses = tag._elses;
+
+//TODO The above works for initial rendering, but when refreshing {^{foo}} need also to associate with {{else}} tags. Use compilation to bind else content templates and expressions with the primary tag template and expression.
+
+ parentView_.tag = tag;
+ // Provide this tag on view, for addMarkerNode on bound tags to add the tag to view._.bnds, associated with the tag id,
+ // for getting the tagCtx and linkCtx during rendering, and so when rendering subsequent {{else}}, will be associated with this tag
+ //TODO does this work with nested elses and with {^{foo:...}} which also adds tag to view, for markerNodes.
+
+// while (tmpl) {
+ // If tagDef has a 'render' function, call it.
+ // If the return result is undefined, return "", or, if a template (or content) is provided,
+ // return the rendered template(using the current data or the first parameter as data);
+ if (render = render || tag.render) {
+ ret = render.apply(tag, args);
+
+// TODO ret = $invoke(tag, render, args);
+ }
+ ret = ret !== undefined
+ ? ret // Return result of render function unless it is undefined, in which case return rendered template
+ : tmpl
+ // render template on args[0] if defined, or otherwise on the current data item
+ ? tag.renderContent(tagCtx.data !== undefined ? tagCtx.data : parentView.data, undefined, parentView)
+ : ""; // No return value from render, and no template defined, so return ::
+
+// tmpl = (tag !== "else" && elses) ? (tagCtx.isElse = tagCtx.isElse || 0, elses[tagCtx.isElse++]) : undefined;
+//}
+
+ // If bind, for {^{tag ... }}, insert script marker nodes
+ return bind ? parentView_.onRender(ret, parentView, bind) : ret;
}
//=================
// View constructor
//=================
- function View(context, path, parentView, data, template, key, onRender, isArray) {
+ function View(context, type, parentView, data, template, key, onRender) {
// Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded)
- var views,
+ var views, parentView_,
+ isArray = type === "array",
+ self_ = {
+ key: 0,
+ useKey: isArray ? 0 : 1,
+ id: "" + viewId++,
+ onRender: onRender,
+ bnd: {}
+ },
self = {
data: data,
tmpl: template,
views: isArray ? [] : {},
parent: parentView,
ctx: context,
- // If the data is an array, this is an 'Array View' with a views array for each child 'Instance View'
- // If the data is not an array, this is an 'Instance View' with a views 'map' object for any child nested views
- // _useKey is non zero if is not an 'Array View' (owning a data array). Uuse this as next key for adding to child views map
- path: path,
- _useKey: isArray ? 0 : 1,
- _onRender: onRender,
+ type: type,
+ // If the data is an array, this is an 'array view' with a views array for each child 'item view'
+ // If the data is not an array, this is an 'item view' with a views 'map' object for any child nested views
+ // _useKey is non zero if is not an 'array view' (owning a data array). Uuse this as next key for adding to child views map
+ get: getView,
_hlp: getHelper,
- renderLink: function(index) {
- var linkTmpl = this.tmpl.tmpls[index];
- return linkTmpl.render(data, context, this);
- }
- };
+ _: self_
+ };
if (parentView) {
views = parentView.views;
- if (parentView._useKey) {
- // Parent is an 'Instance View'. Add this view to its views object
- // self.key = is the key in the parent view map
- views[self.key = "_" + parentView._useKey++] = self;
- // self.index = is index of the parent
- self.index = parentView.index;
+ parentView_ = parentView._;
+ if (parentView_.useKey) {
+ // Parent is an 'item view'. Add this view to its views object
+ // self._key = is the key in the parent view map
+ views[self_.key = "_" + parentView_.useKey++] = self;
} else {
- // Parent is an 'Array View'. Add this view to its views array
+ // Parent is an 'array view'. Add this view to its views array
views.splice(
- // self.key = self.index - the index in the parent view array
- self.key = self.index = key !== undefined
- ? key
- : views.length,
+ // self._.key = self.index - the index in the parent view array
+ self_.key = self.index =
+ key !== undefined
+ ? key
+ : views.length,
0, self);
}
+ // If no context was passed in, use parent context
+ // If context was passed in, it should have been merged already with parent context
+ self.ctx = context || parentView.ctx;
}
return self;
}
- //=================
+ //=============
// Registration
- //=================
+ //=============
+
+ function compileChildResources(parentTmpl) {
+ var storeName, resources, resourceName, settings, compile;
+ for (storeName in jsvStores) {
+ settings = jsvStores[storeName];
+ if ((compile = settings.compile) && (resources = parentTmpl[storeName + "s"])) {
+ for (resourceName in resources) {
+ // compile child resource declarations (templates, tags, converters or helpers)
+ resources[resourceName] = compile(resourceName, resources[resourceName], parentTmpl, storeName, settings);
+ }
+ }
+ }
+ }
- function addToStore(self, store, name, item, process) {
- // Add item to named store such as templates, helpers, converters...
- var key, onStore;
- if (name && typeof name === "object" && !name.nodeType) {
- // If name is a map, iterate over map and call store for key
- for (key in name) {
- store(key, name[key]);
+ function compileTag(name, item, parentTmpl) {
+ var init, tmpl;
+ if (typeof item === "function") {
+ // Simple tag declared as function. No presenter instantation.
+ item = {
+ tagName: name,
+ render: item,
+ depends: item.depends
+ };
+ } else {
+ // Tag declared as object, used as the prototype for tag instantiation (control/presenter)
+ item.tagName = name;
+ if (tmpl = item.template) {
+ item.template = "" + tmpl === tmpl ? ($templates[tmpl] || $templates(tmpl)) : tmpl;
+ }
+ if (item.init !== FALSE) {
+ init = item.init = item.init || function(tagCtx) {};
+ init.prototype = item;
+ (init.prototype = item).constructor = init;
}
- return self;
}
- if (item === undefined) {
- item = name;
- name = undefined;
+ item.renderContent = renderContent;
+ item.attr = "html";
+ if (parentTmpl) {
+ item._parentTmpl = parentTmpl;
}
- if (onStore = $viewsSub.onBeforeStoreItem) {
- // e.g. provide an external compiler or preprocess the item.
- process = onStore(store, name, item, process) || process;
+//TODO item.onError = function(e) {
+// var error;
+// if (error = this.prototype.onError) {
+// error.call(this, e);
+// } else {
+// throw e;
+// }
+// }
+ return item;
+ }
+
+ function compileTmpl(name, tmpl, parentTmpl, storeName, storeSettings, options) {
+ // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object
+
+ //==== nested functions ====
+ function tmplOrMarkupFromStr(value) {
+ // If value is of type string - treat as selector, or name of compiled template
+ // Return the template object, if already compiled, or the markup string
+
+ if (("" + value === value) || value.nodeType > 0) {
+ try {
+ elem = value.nodeType > 0
+ ? value
+ : !rTmplString.test(value)
+ // If value is a string and does not contain HTML or tag content, then test as selector
+ && jQuery && jQuery(value)[0];
+ // If selector is valid and returns at least one element, get first element
+ // If invalid, jQuery will throw. We will stay with the original string.
+ } catch (e) { }
+
+ if (elem) {
+ // Generally this is a script element.
+ // However we allow it to be any element, so you can for example take the content of a div,
+ // use it as a template, and replace it by the same content rendered against data.
+ // e.g. for linking the content of a div to a container, and using the initial content as template:
+ // $.link("#content", model, {tmpl: "#content"});
+
+ // Create a name for compiled template if none provided
+ value = $templates[elem.getAttribute(tmplAttr)];
+ if (!value) {
+ // Not already compiled and cached, so compile and cache the name
+ name = name || "_" + autoTmplName++;
+ elem.setAttribute(tmplAttr, name);
+ $templates[name] = value = compileTmpl(name, elem.innerHTML, parentTmpl, storeName, storeSettings, options); // Use tmpl as options
+ }
+ }
+ return value;
+ }
+ // If value is not a string, return undefined
}
- if (!name) {
- item = process ? process(item) : item
- } else if ("" + name === name) { // name must be a string
- if (item === null) {
- // If item is null, delete this entry
- delete store[name];
- } else {
- store[name] = process ? (item = process(item, name)) : item;
+
+ var tmplOrMarkup, elem;
+
+ //==== Compile the template ====
+ tmpl = tmpl || "";
+ tmplOrMarkup = tmplOrMarkupFromStr(tmpl);
+
+ // If options, then this was already compiled from a (script) element template declaration.
+ // If not, then if tmpl is a template object, use it for options
+ options = options || (tmpl.markup ? tmpl : {});
+ options.tmplName = name;
+ if (parentTmpl) {
+ options._parentTmpl = parentTmpl;
+ }
+ // If tmpl is not a markup string or a selector string, then it must be a template object
+ // In that case, get it from the markup property of the object
+ if (!tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr(tmpl.markup))) {
+ if (tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode)) {
+ // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile
+ tmplOrMarkup = tmplOrMarkup.markup;
}
}
- if (onStore = $viewsSub.onStoreItem) {
- // e.g. JsViews integration
- onStore(store, name, item, process);
+ if (tmplOrMarkup !== undefined) {
+ if (name && !parentTmpl) {
+ $render[name] = function() {
+ return tmpl.render.apply(tmpl, arguments);
+ };
+ }
+ if (tmplOrMarkup.fn || tmpl.fn) {
+ // tmpl is already compiled, so use it, or if different name is provided, clone it
+ if (tmplOrMarkup.fn) {
+ if (name && name !== tmplOrMarkup.name) {
+ tmpl = extendCtx(options, tmplOrMarkup);
+ } else {
+ tmpl = tmplOrMarkup;
+ }
+ }
+ } else {
+ // tmplOrMarkup is a markup string, not a compiled template
+ // Create template object
+ tmpl = TmplObject(tmplOrMarkup, options);
+ // Compile to AST and then to compiled function
+ tmplFn(tmplOrMarkup, tmpl);
+ }
+ compileChildResources(options);
+ return tmpl;
}
- return item;
}
+ //==== /end of function compile ====
- function compileTag(item, name) {
- item = typeof item === "function" ? { render: item } : item;
- item.name = name;
- item.is = "tag";
- return item;
- }
+ function TmplObject(markup, options) {
+ // Template object constructor
+ var htmlTag,
+ wrapMap = $viewsSettings.wrapMap || {},
+ tmpl = $extend(
+ {
+ markup: markup,
+ tmpls: [],
+ links: {},
+ bnds: [],
+ render: renderContent
+ },
+ options
+ );
- function $templates(name, tmpl) {
- // Register templates
- // Setter: Use $.templates( name, tmpl ) or $.templates({ name: tmpl, ... }) to add additional templates to the registered templates collection.
- // Getter: Use var tmpl = $.templates( name ) or $.templates[name] or $.templates.name to return the object for the registered template.
- // Remove: Use $.templates( name, null ) to remove a registered template from $.templates.
- return addToStore(this, $templates, name, tmpl, compile);
+ if (!options.htmlTag) {
+ // Set tmpl.tag to the top-level HTML tag used in the template, if any...
+ htmlTag = rFirstElem.exec(markup);
+ tmpl.htmlTag = htmlTag ? htmlTag[1].toLowerCase() : "";
+ }
+ htmlTag = wrapMap[tmpl.htmlTag];
+ if (htmlTag && htmlTag !== wrapMap.div) {
+ // When using JsViews, we trim templates which are inserted into HTML contexts where text nodes are not rendered (i.e. not 'Phrasing Content').
+ tmpl.markup = $.trim(tmpl.markup);
+ tmpl._elCnt = TRUE; // element content model (no rendered text nodes), not phrasing content model
+ }
+
+ return tmpl;
}
- function $viewsTags(name, tag) {
- // Register template tags
- // Setter: Use $.view.tags( name, tag ) or $.view.tags({ name: tag, ... }) to add additional tags to the registered tags collection.
- // Getter: Use var tag = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the object for the registered tag.
- // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags.
+ function registerStore(storeName, storeSettings) {
- // When registering for {{foo a b c==d e=f}}, tag should corresponnd to a function with the signature:
- // function(a,b). The 'this' pointer will be a hash with properties c and e.
- return addToStore(this, $viewsTags, name, tag, compileTag);
- }
+ function theStore(name, item, parentTmpl) {
+ // The store is also the function used to add items to the store. e.g. $.templates, or $.views.tags
- function $viewsHelpers(name, helperFn) {
- // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded)
- // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection.
- // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function.
- // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers.
- // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}.
- return addToStore(this, $viewsHelpers, name, helperFn);
- }
+ // For store of name 'thing', Call as:
+ // $.views.things(items[, parentTmpl]),
+ // or $.views.things(name, item[, parentTmpl])
+
+ var onStore, compile, items, itemName, childTemplates, childTemplate, thisStore, childStoreName;
+
+ if (name && "" + name !== name && !name.nodeType && !name.markup) {
+ // Call to $.views.things(items[, parentTmpl]),
+
+ // Adding items to the store
+ // If name is a map, then item is parentTmpl. Iterate over map and call store for key.
+ for (itemName in name) {
+ theStore(itemName, name[itemName], item);
+ }
+ return $views;
+ }
+ thisStore = parentTmpl ? parentTmpl[storeNames] = parentTmpl[storeNames] || {} : theStore;
- function $viewsConverters(name, converterFn) {
- // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded)
- // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection.
- // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function.
- // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters.
- // Within a template, access the converter using the syntax: {{myConverter:...}}.
- return addToStore(this, $viewsConverters, name, converterFn);
+ // Adding a single unnamed item to the store
+ if (item === undefined) {
+ item = name;
+ name = undefined;
+ }
+ compile = storeSettings.compile;
+ if (onStore = $viewsSub.onBeforeStoreItem) {
+ // e.g. provide an external compiler or preprocess the item.
+ compile = onStore(thisStore, name, item, compile) || compile;
+ }
+ if (!name) {
+ item = compile(undefined, item);
+ } else if ("" + name === name) { // name must be a string
+ if (item === null) {
+ // If item is null, delete this entry
+ delete thisStore[name];
+ } else {
+ thisStore[name] = compile ? (item = compile(name, item, parentTmpl, storeName, storeSettings)) : item;
+ if (storeName === "template" && (childTemplates = thisStore[name].templates)) {
+ // This is a template which has child templates defined. We will copy child items of parent template to each
+ // child template, since items registered with the parent templates must also be accessible from the child template
+ for (childStoreName in jsvStores) {
+ // Find child items registered for this parent template
+ childStoreName += "s";
+ if (items = item[childStoreName]) {
+ // Copy these items to each child template
+ for (childTemplate in childTemplates ) {
+ childTemplate = childTemplates[childTemplate];
+ // Copy parent items except if overridden by item of same name in child template
+ childTemplate[childStoreName] = extendCtx(childTemplate[childStoreName], items);
+ }
+ }
+ }
+ }
+ }
+ }
+ if (item) {
+ item._is = storeName;
+ }
+ if (onStore = $viewsSub.onStoreItem) {
+ // e.g. JsViews integration
+ onStore(thisStore, name, item, compile);
+ }
+ return item;
+ }
+
+ var storeNames = storeName + "s";
+
+ $views[storeNames] = theStore;
+ jsvStores[storeName] = storeSettings;
}
- //=================
+ //==============
// renderContent
- //=================
+ //==============
- function renderContent(data, context, parentView, key, isLayout, path, onRender) {
- // Render template against data as a tree of subviews (nested template), or as a string (top-level template).
- var i, l, dataItem, newView, itemResult, parentContext, tmpl, props, swapContent, mergedCtx, dynCtx, hasContext,
+ function renderContent(data, context, parentView, key, isLayout, onRender) {
+ // Render template against data as a tree of subviews (nested rendered template instances), or as a string (top-level template).
+ // If the data is the parent view, treat as layout template, re-render with the same data context.
+ var i, l, dataItem, newView, childView, itemResult, parentContext, props, swapContent, tagCtx, isTag, outerOnRender,
self = this,
+ tmpl = self,
+ allowDataLink = self.attr === undefined || self.attr === "html",
result = "";
if (key === TRUE) {
swapContent = TRUE;
key = 0;
}
- if (self.tagName) {
+ if (isTag = self._is === "tag") {
+ tagCtx = self.tagCtx;
// This is a call from renderTag
- tmpl = self.tmpl;
- if (context || self.ctx) {
- // We need to create an augmented context for the view(s) we are about to render
- mergedCtx = {};
- if (self.ctx) {
- // self.ctx is an object with the contextual template parameters on the tag, such as ~foo: {{tag ~foo=expression...}}
- $extend(mergedCtx, self.ctx);
- }
- if (context) {
- // This is a context object passed programmatically from the tag function
- $extend(mergedCtx, context);
- }
- }
- context = mergedCtx;
- props = self.props;
- if ( props && props.link === FALSE ) {
+ tmpl = tagCtx.isElse ? self._elses[tagCtx.isElse-1] : self.tmpl;
+ context = extendCtx(context, self.ctx);
+ props = tagCtx.props || {};
+ if ( props.link === FALSE ) {
// link=false setting on block tag
// We will override inherited value of link by the explicit setting link=false taken from props
// The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect.
context = context || {};
context.link = FALSE;
}
- parentView = parentView || self.view;
- path = path || self.path;
- key = key || self.key;
-// onRender = self.attr === "html" && parentView && parentView._onRender;
- onRender = parentView && parentView._onRender;
+ parentView = parentView || tagCtx.view;
} else {
tmpl = self.jquery && (self[0] || error('Unknown template: "' + self.selector + '"')) // This is a call from $(selector).render
|| self;
- onRender = onRender || parentView && parentView._onRender;
}
if (tmpl) {
if (parentView) {
+ onRender = onRender || parentView._.onRender;
parentContext = parentView.ctx;
- dynCtx = parentView.dynCtx;
if (data === parentView) {
// Inherit the data from the parent view.
// This may be the contents of an {{if}} block
@@ -396,59 +749,48 @@
data = parentView.data;
isLayout = TRUE;
}
- } else {
- parentContext = $viewsHelpers;
}
// Set additional context on views created here, (as modified context inherited from the parent, and to be inherited by child views)
// Note: If no jQuery, $extend does not support chained copies - so limit extend() to two parameters
- // TODO could make this a reusable helper for merging context.
- hasContext = (context && context !== parentContext);
- if (dynCtx || hasContext) {
- parentContext = $extend({}, parentContext);
- if (hasContext) {
- $extend(parentContext, context);
- }
- if (dynCtx) {
- $extend(parentContext, dynCtx);
- }
- }
- context = parentContext;
+ context = extendCtx(context, parentContext);
if (!tmpl.fn) {
tmpl = $templates[tmpl] || $templates(tmpl);
}
if (tmpl) {
- onRender = context.link !== FALSE && onRender; // If link===false, do not call onRender, so no data-linking annotations
+ onRender = (context && context.link) !== FALSE && allowDataLink && onRender;
+ // If link===false, do not call onRender, so no data-linking marker nodes
+ outerOnRender = onRender;
+ if (onRender === TRUE) {
+ // Used by view.refresh(). Don't create a new wrapper view.
+ outerOnRender = undefined;
+ onRender = parentView._.onRender;
+ }
if ($.isArray(data) && !isLayout) {
// Create a view for the array, whose child views correspond to each data item.
// (Note: if key and parentView are passed in along with parent view, treat as
// insert -e.g. from view.addViews - so parentView is already the view item for array)
- newView = swapContent ? parentView : (key !== undefined && parentView) || View(context, path, parentView, data, tmpl, key, onRender, TRUE);
+ newView = swapContent ? parentView : (key !== undefined && parentView) || View(context, "array", parentView, data, tmpl, key, onRender);
for (i = 0, l = data.length; i < l; i++) {
// Create a view for each data item.
dataItem = data[i];
- itemResult = tmpl.fn(dataItem, View(context, path, newView, dataItem, tmpl, (key || 0) + i, onRender), $views);
- result += onRender ? onRender(itemResult, tmpl, props) : itemResult;
+ childView = View(context, "item", newView, dataItem, tmpl, (key || 0) + i, onRender);
+ itemResult = tmpl.fn(dataItem, childView, $views);
+ result += newView._.onRender ? newView._.onRender(itemResult, childView) : itemResult;
}
} else {
// Create a view for singleton data object.
- newView = swapContent ? parentView : View(context, path, parentView, data, tmpl, key, onRender);
- newView._onRender = onRender;
- result += tmpl.fn(data, newView, $views, returnVal);
+ newView = swapContent ? parentView : View(context, "data", parentView, data, tmpl, key, onRender);
+ result += tmpl.fn(data, newView, $views);
}
- return onRender ? onRender(result, tmpl, props, newView.key, path) : result;
+ return outerOnRender ? outerOnRender(result, newView) : result;
}
}
- error("No template found");
return "";
}
- function returnVal(value) {
- return value;
- }
-
//===========================
// Build and compile template
//===========================
@@ -457,8 +799,8 @@
// (Compile AST then build template function)
function error(message) {
- if ($views.debugMode) {
- throw new $views.Error(message);
+ if ($viewsSettings.debugMode) {
+ throw new $views.sub.Error(message);
}
}
@@ -466,21 +808,13 @@
error("Syntax error\n" + message);
}
- function tmplFn(markup, tmpl, bind) {
+ function tmplFn(markup, tmpl, isLinkExpression) {
// Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes
// Used for compiling templates, and also by JsViews to build functions for data link expressions
- var newNode,
- //result,
- allowCode = tmpl && tmpl.allowCode,
- astTop = [],
- loc = 0,
- stack = [],
- content = astTop,
- current = [, , , astTop];
//==== nested functions ====
- function pushPreceedingContent(shift) {
+ function pushprecedingContent(shift) {
shift -= loc;
if (shift) {
content.push(markup.substr(loc, shift).replace(rNewLine, "\\n"));
@@ -491,43 +825,44 @@
tagName && syntaxError('Unmatched or missing tag: "{{/' + tagName + '}}" in template:\n' + markup);
}
- function parseTag(all, defer, tagName, converter, colon, html, code, params, slash, closeBlock, index) {
- // tag converter colon html code params slash closeBlock
- // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g;
- // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup, link ]
+ function parseTag(all, bind, tagName, converter, colon, html, comment, codeTag, params, slash, closeBlock, index) {
+
+ // bind tag converter colon html comment code params slash closeBlock
+ // /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g
+
+ // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, bindings, contentMarkup ]
if (html) {
colon = ":";
converter = "html";
}
var current0,
+ pathBindings = [],
+ code = "",
hash = "",
passedCtx = "",
- // Block tag if not self-closing and not {{:}} or {{>}} (special case) and not a data-link expression (has bind parameter)
- block = !slash && !colon && !bind;
+ // Block tag if not self-closing and not {{:}} or {{>}} (special case) and not a data-link expression
+ block = !slash && !colon && !comment && !isLinkExpression;
//==== nested helper function ====
-
tagName = tagName || colon;
- pushPreceedingContent(index);
+ pushprecedingContent(index);
loc = index + all.length; // location marker - parsed up to here
- if (code) {
+ if (codeTag) {
if (allowCode) {
- content.push(["*", params.replace(rUnescapeQuotes, "$1")]);
+ content.push(["*", "\n" + params.replace(rUnescapeQuotes, "$1") + "\n"]);
}
} else if (tagName) {
if (tagName === "else") {
- current[5] = markup.substring(current[5], index); // contentMarkup for block tag
+ if (rTestElseIf.test(params)) {
+ syntaxError('for "{{else if expr}}" use "{{else expr}}"');
+ }
+ current[6] = markup.substring(current[6], index); // contentMarkup for block tag
current = stack.pop();
content = current[3];
block = TRUE;
- } else if (defer) {
- stack.push(current);
- current = ["!", , , [], ,index];
- content.push(current);
- content = current[3];
}
- params = (params
- ? parseParams(params, bind, defer)
+ if (params) {
+ code = parseParams(params, pathBindings)
.replace(rBuildHash, function(all, isCtx, keyValue) {
if (isCtx) {
passedCtx += keyValue + ",";
@@ -535,35 +870,28 @@
hash += keyValue + ",";
}
return "";
- })
- : "");
+ });
+ }
hash = hash.slice(0, -1);
- params = params.slice(0, -1);
+ code = code.slice(0, -1);
newNode = [
tagName,
converter || "",
- params,
+ code,
block && [],
- "{" + (hash ? ("props:{" + hash + "},") : "") + "data: data" + (passedCtx ? ",ctx:{" + passedCtx.slice(0, -1) + "}" : "") + "}"
+ "{" + (hash ? ("props:{" + hash + "},") : "") + 'params:"' + params + '"' + (passedCtx ? ",ctx:{" + passedCtx.slice(0, -1) + "}" : "") + "},",
+ bind && pathBindings || 0
];
content.push(newNode);
if (block) {
stack.push(current);
current = newNode;
- current[5] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag
- } else if (defer) {
- current[5] = markup.substring(current[5], loc); // contentMarkup for block tag
- current = stack.pop();
+ current[6] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag
}
} else if (closeBlock) {
current0 = current[0];
- blockTagCheck(closeBlock !== current0 && !(closeBlock === "if" && current0 === "else") && current0);
- current[5] = markup.substring(current[5], index); // contentMarkup for block tag
- if (current0 === "!") {
- // defer
- current[5] = markup.substring(current[5], loc); // contentMarkup for block tag
- current = stack.pop();
- }
+ blockTagCheck(closeBlock !== current0 && current0 && current0 !== "else");
+ current[6] = markup.substring(current[6], index); // contentMarkup for block tag
current = stack.pop();
}
blockTagCheck(!current && closeBlock);
@@ -571,161 +899,176 @@
}
//==== /end of nested functions ====
-// result = compiledTmplsCache[markup]; // Only cache if template is not named and markup length < ... Consider standard optimization for data-link="a.b.c"
-// if (!result) {
-// result = markup;
- markup = markup.replace(rEscapeQuotes, "\\$1");
- blockTagCheck(stack[0] && stack[0][3].pop()[0]);
+ var newNode,
+ allowCode = tmpl && tmpl.allowCode,
+ astTop = [],
+ loc = 0,
+ stack = [],
+ content = astTop,
+ current = [, , , astTop];
+
+ markup = markup.replace(rEscapeQuotes, "\\$1");
+
+//TODO result = tmplFnsCache[markup]; // Only cache if template is not named and markup length < ..., and there are no bindings or subtemplates?? Consider standard optimization for data-link="a.b.c"
+// if (result) {
+// tmpl.fn = result;
+// } else {
+
+// result = markup;
- // Build the AST (abstract syntax tree) under astTop
- markup.replace(rTag, parseTag);
+ blockTagCheck(stack[0] && stack[0][3].pop()[0]);
- pushPreceedingContent(markup.length);
+ // Build the AST (abstract syntax tree) under astTop
+ markup.replace(rTag, parseTag);
-// result = compiledTmplsCache[result] = buildCode(astTop, tmpl);
+ pushprecedingContent(markup.length);
+
+ if (loc = astTop[astTop.length-1]) {
+ blockTagCheck("" + loc !== loc && (+loc[6] === loc[6]) && loc[0]);
+ }
+// result = tmplFnsCache[markup] = buildCode(astTop, tmpl);
// }
-// return result;
- return buildCode(astTop, tmpl);
+ return buildCode(astTop, tmpl);
}
function buildCode(ast, tmpl) {
- // Build the template function code from the AST nodes, and set as property on the passed in template object
+ // Build the template function code from the AST nodes, and set as property on the passed-in template object
// Used for compiling templates, and also by JsViews to build functions for data link expressions
- var node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, content, attr, quot,
- tmplOptions = tmpl ? {
- allowCode: allowCode = tmpl.allowCode,
- debug: tmpl.debug
- } : {},
- nested = tmpl && tmpl.tmpls;
+ var i, node, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tagName, converter, params, hash, bindings, bindingPaths, nestedTmpls, nestedTmpl, allowCode, content, markup,
+ code = "",
+ tmplOptions = {},
+ l = ast.length;
- // Use the AST (ast) to build the template function
- l = ast.length;
- code = (l ? "" : '"";');
+ if (tmpl) {
+ if (allowCode = tmpl.allowCode) {
+ tmplOptions.allowCode = TRUE;
+ }
+ if (tmpl.debug) {
+ tmplOptions.debug = TRUE;
+ }
+ bindings = tmpl.bnds;
+ nestedTmpls = tmpl.tmpls;
+ }
for (i = 0; i < l; i++) {
- // AST nodes: [ tagName, converter, params, content, hash, contentMarkup, link ]
+ // AST nodes: [ tagName, converter, params, content, hash, bindings, contentMarkup, link ]
node = ast[i];
- if ("" + node === node) { // type string
- code += '"' + node + '"+';
+
+ // Add newline for each callout to t() c() etc. and each markup string
+ //TODO consider changing to ret += t()...; so debug break points can be inserted on each callout.
+ code += "\nret+=";
+ if ("" + node === node) {
+ // a markup string to be inserted
+ code += '"' + node + '";';
} else {
- tag = node[0];
- if (tag === "*") {
- code = code.slice(0, i ? -1 : -3) + ";" + node[1] + (i + 1 < l ? "ret+=" : "");
+ // a compiled tag expression to be inserted
+ tagName = node[0];
+ if (tagName === "*") {
+ // If this {{* }} tag is at the beginning of the template, start with var ret="";
+ // Otherwise remove the last "+\n" characters and replace with ";" to complete the ret += ...; statement, prior to inserted user code,
+ code = (i ? code.slice(0, -5) : "") + node[1];
} else {
converter = node[1];
params = node[2];
content = node[3];
hash = node[4];
- markup = node[5];
- if (tag.slice(-1) === "!") {
+ bindingPaths = node[5];
+ markup = node[6];
+
+ if (content) {
// Create template object for nested template
- nestedTmpl = TmplObject(markup, tmplOptions, tmpl, nested.length);
+ nestedTmpl = TmplObject(markup, tmplOptions);
// Compile to AST and then to compiled function
buildCode(content, nestedTmpl);
- if (attr = /\s+[\w-]*\s*\=\s*\\['"]$/.exec(ast[i-1])) {
- error("'{{!' in attribute:\n..." + ast[i-1] + "{{!...\nUse data-link");
- }
- code += 'view.renderLink(' + nested.length + ')+';
- nestedTmpl.bound = TRUE;
- nestedTmpl.fn.attr = attr || "leaf";
- nested.push(nestedTmpl);
- } else {
- if (content) {
- // Create template object for nested template
- nestedTmpl = TmplObject(markup, tmplOptions, tmpl, nested.length);
- // Compile to AST and then to compiled function
- buildCode(content, nestedTmpl);
- nested.push(nestedTmpl);
- }
- hasViewPath = hasViewPath || hash.indexOf("view") > -1;
- code += (tag === ":"
- ? (converter === "html"
- ? (hasEncoder = TRUE, "h(" + params)
- : converter
- ? (hasConverter = TRUE, 'c("' + converter + '",view,this,' + params)
- : (getsValue = TRUE, "((v=" + params + ')!=u?v:""')
- )
- : (hasTag = TRUE, 't("' + tag + '",view,this,'
- + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template
- + "," + hash + (params ? "," : "") + params))
- + ")+";
+ nestedTmpls.push(nestedTmpl);
}
+ if (bindingPaths) {
+ // Add leaf binding paths to template
+ bindings.push(bindingPaths);
+ bindingPaths = bindings.length;
+ }
+ hasViewPath = hasViewPath || hash.indexOf("view") > -1;
+ // Add newline for each callout to t() c() etc.
+
+ //TODO consider changing to ret += t()...; so debug break points can be inserted on each callout. At the same time, pass in ret to c() and t()
+ // so they can look at the previous ret, and detect whether this is a jsrender tag within an HTML element tag. If so, don't insert marker nodes,
+ // and make the databinding trigger view refresh on parent view... No need for people to set link=false.
+ code += tagName === ":"
+ ? (converter === "html" && !bindingPaths
+ ? (hasEncoder = TRUE, "h(" + params+ ");")
+ : converter || bindingPaths // Call _cnvt if there is a converter, or binding: {{cnvt: ... }}, {^{: ... }} or {^{cnvt: ... }}
+ ? (hasConverter = TRUE, 'c("' + converter + '",view,this,' + hash + bindingPaths + "," + params + ");")
+ : (getsValue = TRUE, "(v=" + params + ')!=u?v:"";')
+ )
+ : (hasTag = TRUE, 't("' + tagName + '",view,this,'
+ + (content ? nestedTmpls.length : '""') // For block tags, pass in the key (nestedTmpls.length) to the nested content template
+ + "," + hash + bindingPaths + (params ? "," : "") + params) + ");";
}
}
}
+
+ // Include only the var references that are needed in the code
code = fnDeclStr
+ (getsValue ? "v," : "")
+ (hasTag ? "t=j._tag," : "")
- + (hasConverter ? "c=j._convert," : "")
+ + (hasConverter ? "c=j._cnvt," : "")
+ (hasEncoder ? "h=j.converters.html," : "")
- + "ret; try{\n\n"
+ + 'ret=""; try{\n'
+ (tmplOptions.debug ? "debugger;" : "")
- + (allowCode ? 'ret=' : 'return ')
- + code.slice(0, -1) + ";\n\n"
- + (allowCode ? "return ret;" : "")
- + "}catch(e){return j._err(e);}";
+ + code + "\nreturn ret;\n\n}catch(e){return j._err(e);}";
try {
- code = new Function("data, view, j, b, u", code);
+ code = new Function("data, view, j, u", code);
} catch (e) {
syntaxError("Compiled template code:\n\n" + code, e);
}
- // Include only the var references that are needed in the code
if (tmpl) {
tmpl.fn = code;
}
return code;
}
- function parseParams(params, bind, defer) {
- var named,
- fnCall = {},
- parenDepth = 0,