### JsRender Template Composition Example
Source: https://github.com/borismoore/jsrender/blob/master/demos/variants/accessing-templates/05_template-composition-templateobjects.html
This example demonstrates how to render a list of movies using JsRender, passing template objects as parameters for dynamic rendering. It utilizes data structures to define movie information and template references.
```javascript
var movies = [
{ title: "Meet Joe Black", languages: [
{ name: "English" },
{ name: "French" }
], tmpl: "#columnTemplate" },
{
title: "Eyes Wide Shut",
languages: [
{ name: "French" },
{ name: "Esperanto" },
{ name: "Spanish" }
],
tmpl: "#rowTemplate"
},
{
title: "The Inheritance",
languages: [
{ name: "English" },
{ name: "German" }
],
tmpl: "#columnTemplate"
}
];
var myTemplates = {
movieTemplate: $.templates("#movieTemplate"),
columnTemplate: $.templates("#columnTemplate"),
rowTemplate: $.templates("#rowTemplate"),
conditionalTemplate: $.templates("#conditionalTemplate")
};
$( "#movieList" ).html( myTemplates.movieTemplate.render( movies, myTemplates ) );
```
--------------------------------
### Conditional Rendering Example
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Demonstrates the {{if}} tag with 'else if' and 'else' conditions. The rendering depends on the truthiness of the evaluated expressions.
```js
var data = {nickname: "Jim", name: "James"};
var tmpl = $.templates("#personTmpl");
var html = tmpl.render(data);
// result: "Nickname: Jim"
```
--------------------------------
### JsRender Template Rendering Example
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/09_helper-functions.html
An example of rendering a JsRender template with helper functions. It defines a movie object and uses the 'movieList' template to render it, applying the 'format' helper for case conversion.
```javascript
var movie = { title: "Eyes Wide Shut", languages: [ { name: "French" }, { name: "German" }, { name: "Spanish" } ] };
$( "#movieList" ).html( $( "#movieTemplate" ).render( movie ) );
```
--------------------------------
### JsRender Template Syntax Examples
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/20_without-jquery.html
Illustrates JsRender template syntax for displaying data and using built-in tags like 'sort'. These are typically embedded within HTML.
```html
| {{>title}} | {{sort languages tmpl="sortedTemplate"/}} | {{sort languages reverse=true}} {{>name}} {{/sort}} |
{{>name}}
```
--------------------------------
### JsRender Template Composition Example
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/06_template-composition.html
Illustrates including external templates for block tags like {{for}} and {{if}} within a JsRender template. This example shows how to use tmpl attributes to specify templates for different rendering scenarios.
```html
{{include tmpl="#headerTemplate"/}} | {{for languages tmpl="#columnTemplate"/}} | {{for languages tmpl=tmpl/}} | {{for languages tmpl='#conditionalTemplate'/}} | {{include tmpl="#sectionWrapperTemplate"}} {{>title}} {{/include}} {{for languages tmpl='#indexWrapperTemplate'}} {{>name}} {{/for}} |
{{>title}} | Section: {{include tmpl=#content/}} | {{>name}}
{{>name}} {{if name.charAt(0)==='E' tmpl='#rowTemplate'}} {{else tmpl='#columnTemplate'}} {{/if}} {{:#index}}: {{include tmpl=#content/}}
```
--------------------------------
### JsRender Initialization and Rendering Logic
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/12_passing-in-context.html
Initializes data, helper functions, and event handlers for a JsRender example. The `renderList` function is responsible for updating the UI by rendering the template with the current context.
```javascript
var reverse = false,
upperCase = false,
movies = [
{ title: "Meet Joe Black", languages: [ { name: "English" }, { name: "French" } ] },
{ title: "Eyes Wide Shut", languages: [ { name: "French" }, { name: "German" }, { name: "Spanish" } ] }
];
function myFormatFunction(value) {
return upperCase ? value.toUpperCase() : value.toLowerCase();
}
$("#movieList")
.on("click", "#sortBtn", function(){
reverse = !reverse;
renderList();
})
.on("click", "#formatBtn", function(){
upperCase = !upperCase;
renderList();
});
function renderList() {
$("#movieList").html(
$("#movieTemplate").render(
[movies],
{
reverseSort: reverse,
format: myFormatFunction,
buttonCaption: function(val) {
if (val === 'sort') {
return reverse ? "Sort increasing" : "Sort decreasing";
}
return upperCase ? "to lower" : "to upper";
}
}
)
);
}
renderList();
```
--------------------------------
### JsRender: Template registration and rendering
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/02_separators-scenario.html
Register multiple JsRender templates with different configurations, including 'allowCode' and 'useViews', and then render them with provided data. Demonstrates template setup and data binding.
```javascript
var movies = [
{ title: "Meet Joe Black", languages: [
{ name: "English" },
{ name: "French" }
], subtitles: [
{ name: "English" },
{ name: "French" },
{ name: "Chinese" }
] },
{
title: "Eyes Wide Shut",
languages: [
{ name: "French" },
{ name: "German" },
{ name: "Spanish" }
],
subtitles: [
{ name: "English" }
]
}
];
$.templates({
movieTmpl1: "#movieTemplate1",
movieTmpl2: "#movieTemplate2",
movieTmpl3: "#movieTemplate3",
movieTmpl4: {
markup: "#movieTemplate3",
allowCode: true,
useViews: true // Since the {{\* ... }} code inserted uses views (view.parent...) we make sure the default optimization of not using views when not necessary
},
movieTmpl5: {
markup: "#movieTemplate4",
allowCode: true,
useViews: true
}
});
```
```javascript
// Note that by default, rendering simple templates does not create a view hierarchy - which allows for optimized performance. // For the movieList3 and movieList4 we are inserting code that does depend on the view hierarchy (e.g. view.parent... ) so for // those templates we have set useViews: true. We could alternatively use $.views.settings.useViews = true, as a global setting...
$( "#movieList1" ).html( $.render.movieTmpl1( movies ) );
$( "#movieList2" ).html( $.render.movieTmpl2( movies ) );
$( "#movieList3" ).html( $.render.movieTmpl3( movies ) );
$( "#movieList4" ).html( $.render.movieTmpl4( movies ) );
$( "#movieList5" ).html( $.render.movieTmpl4( movies ) );
```
--------------------------------
### Define Template Strings and Data
Source: https://github.com/borismoore/jsrender/blob/master/test/perf-compare.html
Defines various template strings for different templating engines and a sample data object. This setup is used for performance comparison.
```javascript
var times = 250, ret, tmplString, htmlSample, tests = [], movie = { Name: "The Red Violin", ReleaseYear: "1998" }, jqueryTmplTemplate = "{{html Name}} ({{html ReleaseYear}}){{html Name}} ({{html ReleaseYear}}){{html Name}} ({{html ReleaseYear}}){{html Name}} ({{html ReleaseYear}})
", jqueryTmplTemplateEncode = "${Name} (${ReleaseYear})${Name} (${ReleaseYear})${Name} (${ReleaseYear})${Name} (${ReleaseYear})
", jsRenderTemplate = "{{:Name}} ({{:ReleaseYear}}){{:Name}} ({{:ReleaseYear}}){{:Name}} ({{:ReleaseYear}}){{:Name}} ({{:ReleaseYear}})
", jsRenderTemplateEncode = "{{>Name}} ({{>ReleaseYear}}){{>Name}} ({{>ReleaseYear}}){{>Name}} ({{>ReleaseYear}}){{>Name}} ({{>ReleaseYear}})
", dotTemplate = "{{=it.Name}} ({{=it.ReleaseYear}}){{=it.Name}} ({{=it.ReleaseYear}}){{=it.Name}} ({{=it.ReleaseYear}}){{=it.Name}} ({{=it.ReleaseYear}})
", dotTemplateEncode = "{{!it.Name}} ({{!it.ReleaseYear}}){{!it.Name}} ({{!it.ReleaseYear}}){{!it.Name}} ({{!it.ReleaseYear}}){{!it.Name}} ({{!it.ReleaseYear}})
", handlebarsTemplate = "{{{Name}}} ({{{ReleaseYear}}}){{{Name}}} ({{{ReleaseYear}}}){{{Name}}} ({{{ReleaseYear}}}){{{Name}}} ({{{ReleaseYear}}})
", handlebarsTemplateEncode = "{{Name}} ({{ReleaseYear}}){{Name}} ({{ReleaseYear}}){{Name}} ({{ReleaseYear}}){{Name}} ({{ReleaseYear}})
", hoganTemplate = "{{{Name}}} ({{{ReleaseYear}}}){{{Name}}} ({{{ReleaseYear}}}){{{Name}}} ({{{ReleaseYear}}}){{{Name}}} ({{{ReleaseYear}}})
", hoganTemplateEncode = "{{Name}} ({{ReleaseYear}}){{Name}} ({{ReleaseYear}}){{Name}} ({{ReleaseYear}}){{Name}} ({{ReleaseYear}})
", dustTemplate = "{Name|s} ({ReleaseYear|s}){Name|s} ({ReleaseYear|s}){Name|s} ({ReleaseYear|s}){Name|s} ({ReleaseYear|s})
", dustTemplateEncode = "{Name} ({ReleaseYear}){Name} ({ReleaseYear}){Name} ({ReleaseYear}){Name} ({ReleaseYear})
"
```
```javascript
// Compile templates for various engines
tmpl_doT = doT.template( dotTemplate ),
tmpl_doTEncode = doT.template( dotTemplateEncode ),
tmpl_jQueryTmpl = $.template( null, jqueryTmplTemplate ),
tmpl_JsRender = $.templates( null, jsRenderTemplate ),
tmpl_jQueryTmplEncode = $.template( null, jqueryTmplTemplateEncode ),
tmpl_JsRenderEncode = $.templates( null, jsRenderTemplateEncode ),
tmpl_handlebars = Handlebars.compile( handlebarsTemplate ),
tmpl_handlebarsEncode = Handlebars.compile( handlebarsTemplateEncode ),
tmpl_hogan = Hogan.compile( hoganTemplate ),
tmpl_hoganEncode = Hogan.compile( hoganTemplateEncode ),
tmpl_dust = dust.compile( dustTemplate );
tmpl_dustEncode = dust.compile( dustTemplateEncode );
```
```javascript
// For Handlebars, make initial rendering call to do first compilation.
htmlSample = tmpl_handlebars( movie );
tmpl_handlebarsEncode( movie );
$( "#output" ).html( htmlSample );
```
```javascript
// For dust, load the template first
tmpl_dustLoaded = dust.loadSource(tmpl_dust);
tmpl_dustLoadedEncode = dust.loadSource(tmpl_dustEncode);
```
--------------------------------
### Compile and Render Templates from Script Blocks
Source: https://github.com/borismoore/jsrender/blob/master/demos/variants/accessing-templates/03_getting-template-objects-from-script-declaration.html
Compile templates declared in script blocks using $.templates() and render data. This example switches between a title-only template and a detailed template for movie data.
```javascript
var movies = [
{ name: "The Red Violin", releaseYear: "1998", director: "Franois Girard" },
{ name: "Eyes Wide Shut", releaseYear: "1999", director: "Stanley Kubrick" },
{ name: "The Inheritance", releaseYear: "1976", director: "Mauro Bolognini" }
];
/* Get template objects for the script block template declarations */
var titleTemplate = $.templates( "#titleTemplate" ),
detailTemplate = $.templates( "#detailTemplate" ),
details = true;
function switchTemplates() {
var html, button = $("#switchBtn");
details = !details;
/* Render using the other compiled template */
if ( details ) {
button.text( "Show titles only" );
html = detailTemplate.render( movies );
} else {
button.text( "Show full details" );
html = titleTemplate.render( movies );
}
$( "#movieList" ).html( html );
}
$( "#switchBtn" ).click( switchTemplates );
switchTemplates();
```
--------------------------------
### Registering Custom Converters with $.views.converters()
Source: https://context7.com/borismoore/jsrender/llms.txt
Illustrates registering custom value converters for transforming data within {{:}} tags. Includes examples of custom converters like 'upper', 'loc', and 'truncate', as well as built-in converters like 'html' and 'attr'.
```javascript
// Register custom converters
$.views.converters({
upper: function(val) {
return val.toUpperCase();
},
loc: function(val) {
var lang = this.tagCtx.props.lang;
var translations = {
"EN": { "Hello": "Hello", "Goodbye": "Goodbye" },
"FR": { "Hello": "Bonjour", "Goodbye": "Au revoir" },
"ES": { "Hello": "Hola", "Goodbye": "Adios" },
};
return translations[lang] && translations[lang][val] || val;
},
truncate: function(val) {
var len = this.tagCtx.props.length || 20;
return val.length > len ? val.substring(0, len) + "..." : val;
}
});
var data = {
name: "John Smith",
greeting: "Hello",
farewell: "Goodbye",
description: "This is a very long description that should be truncated",
htmlContent: ""
};
var tmpl = $.templates(
// Custom converter
"Name: {{upper:name}}
" +
// Localization converter with parameter
"{{loc:greeting lang='FR'}} - {{loc:farewell lang='ES'}}
" +
// Truncate with length parameter
"{{truncate:description length=25}}
" +
// Built-in HTML encoder (XSS protection)
"Safe: {{>htmlContent}}
" +
"Unsafe: {{:htmlContent}}"
);
var html = tmpl.render(data);
// Output:
// Name: JOHN SMITH
// Bonjour - Adios
// This is a very long des...
// Safe: <script>alert('XSS')</script>
// Unsafe: "
// Built-in attr converter for HTML attributes
var tmpl2 = $.templates('{{:name}}
');
var html = tmpl2.render({ name: "John", tooltip: "User's \"profile\"" });
// Output: John
```
--------------------------------
### JsRender Template Example with Converters
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/03_converters-and-encoding.html
This HTML table row demonstrates various JsRender converters for rendering localized titles, raw synopsis, and HTML-encoded synopsis. It also shows attribute encoding in the 'title' attribute.
```html
| {{loc:title lang='EN'}} |
{{loc:title lang='FR'}} |
{{:synopsis}} |
{{>synopsis}} |
```
--------------------------------
### JsRender If-Else If-Else Block
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Implement complex conditional logic within templates using nested if, else-if, and else blocks. This example checks limits against a calculated product price.
```html
{{if ~limits.maxVal > (product.price*100 - discount)/rate}}
...
{{else ~limits.minVal < product.price}}
...
{{else}}
...
{{/if}}
```
--------------------------------
### Complex Table Row Rendering with Local Variables
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/04_assigning-variables-scenario.html
A comprehensive example of rendering a table row using JsRender. It conditionally sets and retrieves local variables ('summary') based on the 'languages' property, demonstrating dynamic content generation.
```html
| {{>title}} | {{if languages}} {{setvar "summary" languages/}} Alternative languages: {{>languages}}. {{else}} {{setvar "summary"}} Subtitles only: {{>subtitles}} {{/setvar}} Subtitles only. See summary column: {{/if}} | {{:title}}: {{:~getvar('summary')}} |
```
--------------------------------
### Access Helper from Nested Template in JsRender
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/13_associating-helpers-with-templates.html
Within a nested template, contextual helpers passed from the parent can be accessed using the '~' prefix followed by the helper's name. This example shows accessing a 'format' function.
```javascript
ID: {{:~utils.format(id)}}
```
--------------------------------
### Run Bundle and Test Commands
Source: https://github.com/borismoore/jsrender/blob/master/test/unit-tests-browserify.html
Before running the tests, execute the Gulp bundle command and then the NPM test command.
```bash
_$ gulp bundle_
```
```bash
_$ npm test_
```
--------------------------------
### Generate Browserify Client Bundles with Gulp
Source: https://github.com/borismoore/jsrender/blob/master/test/browserify/bundles/browserify-bundles-go-here.txt
Run this command to generate browserify client bundles. These bundles are used in the unit tests.
```bash
$ gulp bundle
```
--------------------------------
### Initialize JsRender and Render Template
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/13_associating-helpers-with-templates.html
This script initializes JsRender with defined templates and helpers, then renders the 'appTmpl' with the provided model data, populating the '#target' element.
```javascript
var people = [
{ id: "abc22", firstName: "Jeff", lastName: "Johnson" },
{ id: "pq44", firstName: "Rachel", lastName: "Roberts" },
{ id: "xyz99", firstName: "Jacques", lastName: "Bertin" }
];
var model = {
suppliers: [people[0], people[2]],
customers: [people[1], people[2]]
}
$.templates({
personTmpl: "#personTmpl",
appTmpl: {
markup:"#appTmpl",
helpers: {
supplierUtils: {
format:function(val){return "Supplier:" + val.toUpperCase();}
},
customerUtils: {
format:function(val){return "Customer:" + val.toLowerCase();}
}
}
}
});
$("#target").html( $.render.appTmpl( model ));
```
--------------------------------
### Using {{include}} for Template Composition
Source: https://context7.com/borismoore/jsrender/llms.txt
Demonstrates registering and using partial templates with the {{include}} tag for template composition. Shows basic includes, includes with modified data contexts, and using #content within wrapper templates.
```javascript
// Register partial templates
$.templates({
streetTmpl: "{{:street}}",
cityTmpl: "{{:city}}",
addressTmpl: "{{include address tmpl='streetTmpl'/}}, {{include address tmpl='cityTmpl'/}}"
});
var data = {
name: "Jim",
address: { street: "Main Street", city: "Boston" }
};
// Basic include with template reference
var tmpl = $.templates("{{:name}}'s address: {{include tmpl='addressTmpl'/}}");
var html = tmpl.render(data);
// Output: "Jim's address: Main Street, Boston"
// Include with changed data context
var tmpl2 = $.templates(
"Name: {{:name}}, " +
"{{include address}}Street: {{:street}}, City: {{:city}}{{/include}}"
);
var html = tmpl2.render(data);
// Output: "Name: Jim, Street: Main Street, City: Boston"
// Wrapper template with #content
$.templates("sectionWrapper", "{{:title}}
{{include tmpl=#content/}}
");
var tmpl3 = $.templates(
"{{include tmpl='sectionWrapper' title='Address'}}" +
"{{:address.street}}, {{:address.city}}" +
"{{/include}}"
);
var html = tmpl3.render(data);
// Output: "Address
Main Street, Boston
"
```
--------------------------------
### Compile templates
Source: https://github.com/borismoore/jsrender/blob/master/test/perf-compare.html
Measures the performance of compiling templates across different JavaScript templating engines. This is crucial for understanding the initial setup cost of each library.
```javascript
test( "jQuery Templates compile", times * 5, 0, function() { tmpl_jQueryTmpl = $.template( jqueryTmplTemplate ); });
```
```javascript
test( "doT compile", times * 5, 0, function() { tmpl_doT = doT.template( dotTemplate ); });
```
```javascript
test( "Handlebars compile", times * 5, 0, function() { var tmpl = Handlebars.compile( handlebarsTemplateEncode ); // For Handlebars, make initial rendering call to do first compilation. tmpl( movie ); });
```
```javascript
test( "Hogan compile", times * 5, 0, function() { Hogan.cache = {}; // Clear cached compiled template tmpl_hogan = Hogan.compile( hoganTemplate ); });
```
```javascript
test( "Dustjs compile", times * 5, 0, function() { tmpl_dust = dust.compile( dustTemplate ); tmpl_dustLoaded = dust.loadSource(tmpl_dust); });
```
```javascript
test( "JsRender compile", times * 5, 0, function() { tmpl_JsRender = $.templates( "test", jsRenderTemplate ); });
```
--------------------------------
### Initiate String Rendering Performance Tests
Source: https://github.com/borismoore/jsrender/blob/master/test/perf-compare.html
Appends headers and initiates the performance tests for rendering to a string for various templating engines.
```javascript
// Test render to string perf
$( "#results" ).append( "| ________________________________________ |
" );
$( "#results" ).append( "| Render to string |
");
```
```javascript
test( "jQuery Templates", times * 100, 1, function() {
ret = tmpl_jQueryTmpl($, { data: movie }).join("");
});
```
```javascript
test( "doT", times * 500, 1, function() {
ret = tmpl_doT(movie);
});
```
```javascript
test( "Handlebars", times * 500, 1, function() {
ret = tmpl_handlebars(movie);
});
```
```javascript
test( "Hogan", times * 500, 1, function() {
ret = tmpl_hogan.render(movie);
});
```
```javascript
test( "Dustjs", times * 500, 1, function() {
dust.render(tmpl_dustLoaded, movie, function(err, out) {
ret = out;
});
});
```
```javascript
test( "JsRender", times * 500, 1, function() {
ret = tmpl_JsRender.render( movie );
});
```
--------------------------------
### JsRender: Helper function definitions
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/02_separators-scenario.html
Define custom helper functions for use within JsRender templates. This example shows helpers for checking if an item is next-to-last or not the last in a collection.
```javascript
$.views.helpers({ nextToLast: function() { return this.index === this.parent.data.length-2; }, notLast: function() { return this.index !== this.parent.data.length-1; } });
```
--------------------------------
### Express.js Integration with JsRender
Source: https://context7.com/borismoore/jsrender/llms.txt
Configures an Express.js application to use JsRender as its view engine for rendering HTML templates. This setup allows rendering views directly within Express routes.
```javascript
// Express.js integration
app.engine('html', jsrender.__express);
app.set('view engine', 'html');
app.get('/movie/:id', function(req, res) {
res.render('movie', { title: "Movie Title", year: 2010 });
});
```
--------------------------------
### Retrieve and Render Local Variable using {{:getvar}}
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/04_assigning-variables-scenario.html
Illustrates retrieving the value of the 'summary' local variable using the 'getvar' helper and rendering it in the template.
```html
{{:~getvar('summary')}}
```
--------------------------------
### Basic jsrender Usage with AMD
Source: https://github.com/borismoore/jsrender/blob/master/test/test-amd-scriptloader-no-jquery.html
Demonstrates basic jsrender usage with Asynchronous Module Definition (AMD). Ensures no global variables are created and no jQuery dependency is used.
```javascript
require(["../jsrender"], function($) { alert($.templates("Name: {{:name}}").render({name: "Jo"}) + "\nNo globals and no jQuery: " + (!window.jsrender && !window.jQuery && !$.fn && !!$.views.helpers)); });
```
--------------------------------
### JsRender conditional rendering in table cell
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/10_comparison-tests.html
Conditionally render content within a table cell based on the 'languages' property. This example shows how to use JsRender's {{if}} tag with different conditions.
```html
| {{>title}} | {{if !(languages && languages.length) tmpl="#messageTmpl"/}} | {{if languages==null tmpl="#messageTmpl"/}} |
```
--------------------------------
### Use Custom Tag
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Demonstrates how to use a custom tag defined either as a render function or a template string. The tag is invoked within a template.
```js
var tmpl = $.templates("{{fullName person/}}");
var data = {person: {first: "Jim", last: "Varsov"}};
var html = tmpl.render(data);
// result: "Jim Varsov"
```
--------------------------------
### Declare Custom Helper for Getting Local Variables
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/04_assigning-variables-scenario.html
Defines a custom 'getvar' helper function to retrieve values stored in local variables. This helper can be used anywhere in the template to access previously set variables.
```javascript
$.views.helpers({
getvar: function(key) {
return vars[key];
}
})
```
--------------------------------
### Registering Global Helpers with $.views.helpers()
Source: https://context7.com/borismoore/jsrender/llms.txt
Shows how to register global helper functions and values using $.views.helpers(). These helpers can be accessed within templates using the ~helperName syntax.
```javascript
// Register global helpers
$.views.helpers({
format: function(val, fmt) {
switch (fmt) {
case "upper": return val.toUpperCase();
case "lower": return val.toLowerCase();
case "title": return val.charAt(0).toUpperCase() + val.slice(1).toLowerCase();
}
return val;
},
currency: function(val) {
return "$" + val.toFixed(2);
},
appTitle: "My Movie Database"
});
var data = {
title: "eyes wide shut",
price: 19.99,
languages: [
{ name: "FRENCH" },
{ name: "GERMAN" }
]
};
var tmpl = $.templates(
"{{:~appTitle}}
" +
"{{:~format(title, 'title')}}
" +
"Price: {{:~currency(price)}}
" +
"{{for languages}}" +
" {{:~format(name, 'lower')}}
" +
"{{/for}}"
);
var html = tmpl.render(data);
// Output:
// My Movie Database
// Eyes Wide Shut
// Price: $19.99
// french
// german
// Pass helpers during render (overrides global)
var localHelpers = {
format: function(val) { return "*** " + val + " ***"; }
};
var html = tmpl.render(data, localHelpers);
```
--------------------------------
### Register and Render Named Template
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Register a named template using $.templates() and then render it using the $.templates.templateName or $.render.templateName syntax.
```javascript
// Register named template - "myTmpl1
$.templates("myTmpl1", "Name: {{:name}}
");
var person = {name: "Jim"};
// Render named template
var html = $.templates.myTmpl1(person);
// Alternative syntax: var html = $.render.myTmpl1(person);
// result: "Name: Jim
"
```
--------------------------------
### JsRender Custom Tag for Default Value
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/01_default-values-scenario.html
Define a custom JsRender tag to handle default values. This approach allows for more complex logic than simple expressions. The 'get' tag retrieves a value or uses a provided 'defaultValue' from its context.
```html
{{get languages defaultValue="No languages!"/}}
```
```javascript
$.views.tags({
get: function( value ) {
return value || this.ctx.props.defaultValue;
}
});
```
```html
{{get path default="..."}}
```
--------------------------------
### JsRender Rendering with Data
Source: https://github.com/borismoore/jsrender/blob/master/demos/variants/accessing-templates/04_template-composition-subtemplates.html
Render the main template with the provided data and insert the output into a DOM element. This initiates the template rendering process.
```javascript
$( "#movieList" ).html( $.render.movieTemplate( movies ) );
```
--------------------------------
### JsRender Template Rendering
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/07_paths.html
Initializes JsRender and renders the 'people' data using the '#peopleTemplate'. The output is then inserted into the HTML element with the ID 'peopleList'.
```javascript
$( "#peopleList" ).html( $( "#peopleTemplate" ).render( people ) );
```
--------------------------------
### Assign Value to Local Variable using {{setvar}}
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/04_assigning-variables-scenario.html
Demonstrates using the 'setvar' custom tag to assign a static string value to a local variable named 'summary'.
```html
{{setvar "summary" languages/}}
```
--------------------------------
### JsRender Template Markup for App
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/13_associating-helpers-with-templates.html
This is the main application template markup, which includes sections for suppliers and customers, each rendering a 'personTmpl' with potentially different contextual helpers.
```html
JsRender Sub-templates
```
--------------------------------
### Compile and Render Template in Node.js
Source: https://context7.com/borismoore/jsrender/llms.txt
Compiles a JsRender template from a file and renders it with data in a Node.js environment. Ensure the template file path is correct.
```javascript
// On Node.js
var jsrender = require('jsrender');
// Compile template from file
var tmpl = jsrender.templates('./views/movie.html');
// Render with data
var html = tmpl.render({ title: "Inception", year: 2010 });
```
--------------------------------
### Define Custom Tag with Render Function
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Create a custom tag by providing a render function. This function receives the data context and returns the rendered string.
```js
$.views.tags("fullName", function(val) {
return val.first + " " + val.last;
});
```
--------------------------------
### Initiate HTML Encoding Performance Tests
Source: https://github.com/borismoore/jsrender/blob/master/test/perf-compare.html
Appends headers and initiates the performance tests for HTML encoding for various templating engines.
```javascript
// Test html encoding perf
$( "#results" ).append( "| ________________________________________ |
" );
```
--------------------------------
### tmpl.render() - Render Template with Data
Source: https://context7.com/borismoore/jsrender/llms.txt
The render() method executes a compiled template against data. When passed an array, it iterates automatically and concatenates results. Helpers can be passed as the second argument for use within templates.
```APIDOC
## tmpl.render() - Render Template with Data
### Description
Executes a compiled template against data. It automatically iterates over arrays and concatenates the results. Optional helpers can be provided as the second argument.
### Method
`tmpl.render(data, [helpers])`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
var tmpl = $.templates("{{:#index+1}}: {{>name}} ({{>releaseYear}})
");
// Render with a single object
var person = { name: "Jim", releaseYear: "1999" };
var html = tmpl.render(person);
// Output: "1: Jim (1999)
"
// Render with an array - iterates automatically
var movies = [
{ name: "The Red Violin", releaseYear: "1998" },
{ name: "Eyes Wide Shut", releaseYear: "1999" },
{ name: "The Inheritance", releaseYear: "1976" }
];
var html = tmpl.render(movies);
// Output: "1: The Red Violin (1998)
2: Eyes Wide Shut (1999)
3: The Inheritance (1976)
"
// Render with helpers
var myHelpers = {
upper: function(val) { return val.toUpperCase(); },
title: "Sir"
};
var tmpl2 = $.templates("{{:~title}} {{:first}} {{:~upper(last)}}");
var html = tmpl2.render({ first: "Jim", last: "Varsov" }, myHelpers);
// Output: "Sir Jim VARSOV"
```
### Response
#### Success Response (200)
Returns the rendered HTML string.
#### Response Example
(See Request Example for output strings.)
```
--------------------------------
### Register Global Helpers
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Register helpers globally using $.views.helpers(). This makes them available to all templates rendered subsequently.
```js
$.views.helpers(myHelpers);
var data = {first: "Jim", last: "Varsov"};
var html = tmpl.render(data);
// result: "Sir Jim VARSOV"
```
--------------------------------
### JsRender Template Accessing Root Data and Helper Function
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/11_accessing-parent-data.html
Demonstrates accessing root data with ~root and calling a helper function, passing nested data as arguments.
```html
{{for movies}} | '{{>title}}': showing at the '{{>~root.theater}}' | {{for languages ~title=title}} {{>#data}}{{>~root.specialMessage(#data, ~title)}} {{/for}} |
{{/for}}
```
--------------------------------
### Browserify Done Object
Source: https://github.com/borismoore/jsrender/blob/master/test/unit-tests-browserify.html
Initializes the browserify done object for test execution.
```javascript
window.browserify = {done: {}};
```
--------------------------------
### Define Template from HTML File (Node.js)
Source: https://github.com/borismoore/jsrender/blob/master/README.md
On Node.js, define a jsrender template from an HTML file. Ensure the 'jsrender' module is required.
```javascript
var $ = require('jsrender'); // returns the jsrender namespace object
var tmpl = $.templates("./templates/myTemplate.html");
```
--------------------------------
### Render Template with Data using tmpl.render()
Source: https://context7.com/borismoore/jsrender/llms.txt
The render() method executes a compiled template against data. It automatically iterates over arrays and concatenates results. Helpers can be passed as the second argument for use within templates.
```javascript
var tmpl = $.templates("{{:#index+1}}: {{>name}} ({{>releaseYear}})
");
// Render with a single object
var person = { name: "Jim", releaseYear: "1999" };
var html = tmpl.render(person);
// Output: "1: Jim (1999)
"
```
```javascript
// Render with an array - iterates automatically
var movies = [
{ name: "The Red Violin", releaseYear: "1998" },
{ name: "Eyes Wide Shut", releaseYear: "1999" },
{ name: "The Inheritance", releaseYear: "1976" }
];
var html = tmpl.render(movies);
// Output: "1: The Red Violin (1998)
2: Eyes Wide Shut (1999)
3: The Inheritance (1976)
"
```
```javascript
// Render with helpers
var myHelpers = {
upper: function(val) { return val.toUpperCase(); },
title: "Sir"
};
var tmpl2 = $.templates("{{:~title}} {{:first}} {{:~upper(last)}}");
var html = tmpl2.render({ first: "Jim", last: "Varsov" }, myHelpers);
// Output: "Sir Jim VARSOV"
```
--------------------------------
### Set Contextual Template Parameters in JsRender
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/11_accessing-parent-data.html
Shows how to set contextual template parameters using ~theater=theater, which are accessible in nested contexts as ~theater.
```html
{{for movies ~theater=theater}}
| '{{>title}}': showing at the '{{>~theater}}' |
```
--------------------------------
### Define Custom Tag with Template String
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Define a custom tag using a template string. This is a concise way to create tags for simple rendering logic.
```js
$.views.tags("fullName", "{{:first}} {{:last}}");
```
--------------------------------
### Render and insert in DOM
Source: https://github.com/borismoore/jsrender/blob/master/test/perf-compare.html
Benchmarks the performance of rendering templates and directly inserting the output into the DOM. This test focuses on the efficiency of DOM manipulation after rendering.
```javascript
test( "jQuery Templates - inserted in DOM", times * 5, 0, function() { $( "#output" ).empty(); $.tmpl( tmpl_jQueryTmpl, movie ).appendTo( "#output" ); });
```
```javascript
test( "JsRender - inserted in DOM", times * 5, 0, function() { $( "#output" ).html(tmpl_JsRender.render( movie )); });
```
--------------------------------
### JsRender Data and Rendering
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/06_template-composition.html
Defines movie data and renders it using a JsRender template. This snippet shows how to prepare data and use the .render() method to display it in the HTML.
```javascript
var movies = [
{ title: "Meet Joe Black", languages: [ { name: "English" }, { name: "French" } ], tmpl: "#columnTemplate" },
{ title: "Eyes Wide Shut", languages: [ { name: "French" }, { name: "Esperanto" }, { name: "Spanish" } ], tmpl: "#rowTemplate" },
{ title: "The Inheritance", languages: [ { name: "English" }, { name: "German" } ], tmpl: "#columnTemplate" }
];
$( "#movieList" ).html( $( "#movieTemplate" ).render( movies ) );
```
--------------------------------
### Template Composition with Include Tag
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Use the {{include ...}} tag for template composition. It can evaluate block content or a specified template against a modified data context.
```javascript
var data = {name: "Jim", address: {street: "Main Street"} };
// Register two named templates
$.templates({
streetTmpl: "{{:street}}",
addressTmpl: "{{:name}}'s address is {{include address tmpl='streetTmpl'/}}."
});
// Render outer template
var html = $.templates.addressTmpl(data);
// result: "Jim's address is Main Street"
```
--------------------------------
### Render with Passed Helpers
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Pass helpers directly to the render method. This allows for localized helper scope for specific rendering operations.
```js
var data = {first: "Jim", last: "Varsov"};
var html = tmpl.render(data, myHelpers);
// result: "Sir Jim VARSOV"
```
--------------------------------
### JsRender Template: Nested Layout with Include
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/05_arrays-plus-headers-and-footers.html
A JsRender template demonstrating nested layouts using the {{include}} tag.
```jsrender
{{include languages}}
header
{{for}}
item
{{/for}}
footer
{{/for}}
```
--------------------------------
### Render Template with Object Data
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Render a jsrender template using an object as the data context. The result is HTML ready for insertion.
```javascript
var tmpl = $.templates(" Name: {{:name}}
");
var person = {name: "Jim"};
// Render template for person object
var html = tmpl.render(person); // ready for insertion, e.g $("#result").html(html);
// result: "Name: Jim
"
```
--------------------------------
### JsRender Template with Nested Loops and Data Access
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/11_accessing-parent-data.html
A comprehensive JsRender template demonstrating nested loops, parent data access, and calling a helper function.
```html
{{for movies}}
| '{{>title}}': showing at the '{{>#parent.parent.data.theater}}' | {{if languages}} {{for languages}} {{>#data}}{{>#parent.parent.parent.parent.parent.data.specialMessage(#data, #parent.parent.data.title)}} {{/for}} {{/if}} |
{{/for}}
```
--------------------------------
### JsRender Template with Contextual Parameters and Helper Call
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/11_accessing-parent-data.html
This template uses contextual parameters like ~theater and ~specialMessage, and calls a helper function with nested data.
```html
{{for movies ~theater=theater ~specialMessage=specialMessage}} | '{{>title}}': showing at the '{{>~theater}}' | {{for languages ~title=title}} {{>#data}}{{>~specialMessage(#data, ~title)}} {{/for}} |
{{/for}}
```
--------------------------------
### JsRender Template Rendering with Data
Source: https://github.com/borismoore/jsrender/blob/master/demos/scenarios/01_default-values-scenario.html
Renders movie data using different JsRender templates, demonstrating the application of default values and custom tags within table structures. The code initializes JsRender tags and then renders the data using jQuery.
```javascript
$.views.tags({
get: function( value ) {
return value || this.tagCtx.props.defaultValue;
},
yesNo: function( value ) {
return value ? this.tagCtx.props.yes : this.tagCtx.props.no;
}
});
```
```javascript
var movies = [
{ title: "Meet Joe Black", languages: "English and French" },
{ title: "Eyes Wide Shut" },
{ title: "The Mighty" },
{ title: "City Hunter", languages: "Mandarin and Chinese" }
];
```
```javascript
$( "#movieList1" ).html( $( "#movieTemplate1" ).render( movies ) );
$( "#movieList2" ).html( $( "#movieTemplate2" ).render( movies ) );
$( "#movieList3" ).html( $( "#movieTemplate3" ).render( movies ) );
```
--------------------------------
### Passing Context to render()
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/12_passing-in-context.html
Use the `helpersOrContext` parameter of the `render()` method to pass data and helper functions to your template. Access these using the `~name` syntax.
```javascript
$( selector ).render( data, {
reverseSort: reverse,
format: myFormatFunction,
buttonCaption: function(val) {
...
}
})
```
--------------------------------
### Render Movie List with JsRender Template
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/08_custom-tags.html
Renders a list of movies using a JsRender template. Ensure the '#movieList' element and '#movieTemplate' exist in your HTML.
```javascript
var movies = [
{ title: "Meet Joe Black", languages: [
{ name: "English" },
{ name: "French" }
] },
{ title: "Eyes Wide Shut", languages: [
{ name: "French" },
{ name: "German" },
{ name: "Spanish" }
] }
];
$("#movieList").html($("#movieTemplate").render(movies));
```
--------------------------------
### Access Top-Level Data in JsRender
Source: https://github.com/borismoore/jsrender/blob/master/demos/step-by-step/11_accessing-parent-data.html
Illustrates accessing top-level data in nested contexts using ~root.theater.
```html
{{for movies}}
| '{{>title}}': showing at the '{{>~root.theater}}' |
```
--------------------------------
### Render Object Properties with {{props}} Tag
Source: https://github.com/borismoore/jsrender/blob/master/README.md
Renders an object's properties using the {{props}} tag and a specified template. The data context for each property includes its key and value.
```js
var data = {person: {first: "Jim", last: "Varsov"} };
var tmpl = $.templates("#personTmpl");
var html = tmpl.render(data);
// result: ""
```