Working with jQuery Templates Tip jQuery Templates

October 4, 2010 was published about the announcement of three jQuery plugins, created with the support of the Microsoft team. These plugins are the jQuery Templates plugin, the jQuery Data Link plugin and globalization plugin (the jQuery Globalization plugin)– got the status “Official plugins of the jQuery project” (officially supported plugins of the jQuery project).

The template plugin is used when it is necessary to display a data object or an array of objects in the page markup. A data binding plugin is needed to link objects to page elements and change values ​​synchronously. The globalization plugin allows you to display data such as numbers, date and time, amount of money, etc. on the page in accordance with the format of the current language.

It should be noted that the Microsoft team used their considerable expertise in these areas, as did the jQuery project team, and with a well-established interaction, they turned out, in my opinion, excellent tools for developers. In support of my opinion, I can add that the jQuery developers announced the inclusion of template plugins and data binding in the core jQuery library already in version 1.5, and the globalization plugin in the corresponding version of jQuery UI. The plugins have not yet received the release status, but the documentation on the site is already being actively written. By the way, the Microsoft team followed the traditions of jQuery development and posted plugin development materials on github.com, where plugin descriptions and sources are available.

In this article, I will talk a little about the template plugin.

jQuery Templates plugin

Let's start with a simple example:

So, in the example, the page developer described a template for displaying objects in the form of markup (the first element script ), then I got an array of objects from somewhere movies and called the instruction to generate the required markup according to the template, taking data from the provided array of objects, and adding the result to the end of the list #movielist .
As a result of the plugin, we will get the following markup:

  • The Red Violin (1998)
  • Eyes Wide Shut (1999)
  • The Inheritance (1976)

And now to the point.
What does the plugin do?
The plugin receives as input a template string and a set of objects (or one object) that needs to be output to a string (or markup) with formatting.
Where does it apply?
Basically, this plugin is useful for dynamically displaying JS objects on a page, objects can be obtained in a variety of ways, for example, during calculations or as a result of some user actions and, of course, the most frequently cited example, in the form of JSON in the server response to an AJAX request .

Plugin Methods

.tmpl([ data ], [ options ])
Gets the content of the first selected element and uses it as a template for the formatted output of the specified data.
data – data to be output to the template (object or array of objects).
options – optionally, a user-defined extension in the form of key-value pairs for the output object to the template.
jQuery.tmpl(template, [ data ], [ options ])
Uses the specified template to format the output of the specified data.
template – a template for data formatting, can be one of the following types: a string with markup, an HTML element (including in a jQuery wrapper), a string corresponding to the name of a previously compiled template.
data, options - have the same meaning as above
.tmplItem()
Returns for the first selected element a structure (object) with the results of the templating engine. The object returned by the method provides access to:

  • The HTML parts that make up the template
  • associated unit of transmitted data
  • parent template if current template is nested
  • the current template used for the output
  • user-defined extension (fields and methods) passed in the options parameter of the tmpl() method

This method is used, for example, when, after the data has been formatted, it is required to find out what data was used to form a certain piece of markup, or to update a piece of markup using new data.
jQuery.tmplItem(element)
Similar to the .tmplItem method, only the structure with the results of the template engine is searched for the element element (HTML element, including jQuery wrapper).
.template([ name ])
The method makes a compiled version of the format template from the contents of the first selected element.
name - optional template name, if the name is specified, then you can use it to refer to this template in the method jQuery.tmpl(name, data, options)
jQuery.template([name, ]template)
The method is similar to the one described above, only here the template is passed as a parameter template - it can be a string, a string with markup, an HTML element (including in a jQuery wrapper).

Template Syntax

I will briefly describe a few of the most basic elements of the template, I hope to describe the rest in more detail in the next article (if there is a positive response to this article)
$(fieldNameOrExpression) and ((= fieldNameOrExpression))
Allows you to insert the value of a field (property) of a data object into the template; it can also be used to insert the result of a method or js expression. For example, "$(Name)" - inserts the value of the obj.Name field into the template, and despite the fact that Languages ​​is a field of the object to which the array is assigned, "$(Languages.length)" - will insert the length of this array into the template, and finally, if the object has a getLanguages ​​method with two parameters, then "$(getLanguages(Languages, ' - '))" – inserts the result of this method into the template.
((html fieldNameOrExpression))
The template element $(field) (or ((= field))) inserts the value of the specified field into the result as text, i.e. if there are HTML tags in the string, they will be encoded, not converted to markup. If you need to insert data into the template in the form of HTML markup, then you need to use the syntax ((html<что нужно вставить>}} .
Enough has already been said to get started with the plugin, I can only add that the template syntax allows you to insert nested templates, conditional statements, access some JS and jQuery objects, and something else ... The rest is the material of a future article.

Sources

The article is based on materials found on the World Wide Web. Basically, this is a translation of official documentation. The originals can be viewed at the following links:

  • (examples taken from there)

about the author

My name is Andrei Zaitsev, profile on the zandroid forum

This is my first article on this blog, and I hope it won't be the last. Many thanks to Gennady for the opportunity to publish it and for the helpful tips on writing and designing the material.

Examples

Example 1: Dynamically Switching the Applied Template

Click for details:



Quite complex and voluminous, it uses several plugin methods at once, taken from.

Example 2: Inserting markup data into a template



In this example, both simple string field values ​​and markup values ​​are added to the template, taken from here.

P.S.

I didn’t write examples, if the audience supports my undertakings, then I can describe step by step what, how and why, and give a few more examples.

Please ask questions about the plugin on the forum, if there are comments specifically on the article, then comment below.

Plugin for the implementation of changing words with various animated effects. CSS effect is suitable for the implementation of promo sites and animated banners.

Implementation of splitting page content into tabs (tabs) using animated CSS3 effects. Four versions: horizontal and vertical tabs with various animated effects.

3. Responsive jQuery slider based on IMPRESS.JS plugin

Cool slider with an imitation of a 3D effect when scrolling through slides. When you increase/decrease the screen size - the size of the font, images and all elements on the slide changes, which guarantees the correct display at any screen expansion. Automatic scrolling is provided.

jQuery solution for creating convenient navigation through sections of a document without reloading the page. Each section is displayed in a separate block with vertical scrolling, and the transition between them can be done both with a mouse click and using the title (with a large screen expansion, the title is displayed on the left side, when viewing the site on a small screen - on top of the document).

Implementation of content navigation in the form List of categories → List of sections → Section content. Navigation is accompanied by various JS effects.

Scrolling through slides is carried out with a Parallax effect (moving layers at different speeds, together creating a 3D effect). The size of the slider changes in proportion to the size of the browser window.

Slideshow with music. It is possible to pause or skip a musical composition.

11. A peculiar menu on jQuery and CSS

When a menu item is selected, the area with its contents is expanded on top.

Dropdown horizontal menu with an interesting jQuery effect of nested items.

Awesome jQuery CSS plugin, will be a very useful addition to any web studio or freelancer's website. With it, you can visually display examples of work performed, broken down by time. The timeline itself is displayed at the bottom, and the completed work is displayed at the top. To navigate between jobs, you can use either the scale or the left/right arrows.

14. TouchTouch gallery optimized for mobile browsing

15. CSS3 Cycle Slider Image Slider

When you click on the name, an image with a description pops up. Only CSS3 is used.
Gallery tutorial.

17. Cool colorful jQuery and CSS3 tooltips

jQuery tooltips in 7 styles. Easy to connect and use in your projects.

If there are more than 5 images in the gallery, left/right arrows appear to navigate through the photos.

Slides can be not only images, but also other HTML content.

Plugin for creating photorealistic shadows.

Fresh implementation of the slider.

26. Transfer text "Bacon"

An unusual effect of wrapping text on a page to a new line along a curve or a given line with a certain offset step.

The plugin automatically calculates the font size for each word so that all text occupies the same area in width, regardless of the number of words in a line.

28. Selecting the type of block display using CSS3

Four types of block display: image with description in three columns, image with description in one column, only images, only text description. To switch the type of display of blocks, you must use the icons on top.

It provides the ability to use templates that make it easy to generate HTML elements from JavaScript data objects.

To avoid misunderstandings, I want to warn you that this module is not actively developed or currently maintained, and the jQuery development team does not recommend its use. This does not mean that you should not use it, but I felt it was my duty to tell you about it before you include it in your projects. I'd be happy to recommend another actively developed option, but I haven't been able to find a replacement for jQuery Templates that even comes close. But even with the mentioned attitude of the developers towards it, this module is still the best.

The history of the jQuery Templates module is rather unusual. At the time, Microsoft and the jQuery development team announced that three plug-ins developed by Microsoft have been given "official" status, something that no plug-in has previously been given.

Some time later, the jQuery team announced they were deprecating these modules and removing them from official status, as well as their plans to replace them with other functionality. The intended replacement was to be part of the jQuery UI library. It's unfortunate but true that nothing that was promised has yet been delivered, and deprecated plugins are still available and widely used (especially the templating plugin).

Obviously, it is up to each individual to decide whether or not to use deprecated code, but I personally like the functionality provided by templates and use them often. In doing so, I assume that I can look at the source code at any time and fix any serious problem if it arises, and that sometimes you still have to find workarounds to overcome minor difficulties, it pays off with the benefits that the use of templates provides. .

Setting up the jQuery Templates Library

Before using jQuery templates, you need to download the jQuery Templates library and include it in your document.

Unzip the archive and copy the jQuery.tmpl.js (development version) or jQuery.tmpl.min.js (deployment version) file to your web server. The next thing to do is to add a script element to the sample document that includes the template library, as shown in the example below:

jQuery Library

Flower shop



We will use this code as a sample document in this article. You may have noticed that it differs from the original version discussed earlier not only in that a template library has been added to it, but also in the fact that elements corresponding to various types of flower products have been removed from it. This is done specifically so that we can restore these elements in the document in various ways using the template library.

The appearance of the source document in the browser window at this stage is shown in the figure:

A simple data template example

The best way to learn about data patterns is to jump right into it. To demonstrate the main features of templates, we use the code from the example below:

... ...

In the following sections, we will break the example into separate parts and analyze the code for each of them separately. When data is part of a document, it is called inline data. The alternative is remote data, stored on the server separately from the document. We'll look at remote data a bit later, but for now, you'll notice that this issue is closely related to the Ajax support provided by the jQuery library.

Data definition

The example starts by defining the data. In our case, the data is an array of objects, each of which describes a separate type of flower production. The relevant code snippet is below:

Var data = [ ( name: "Astra", product: "astor", stocklevel: "10", price: 2.99), ( name: "Narcissus", product: "daffodil", stocklevel: "12", price: 1.99 ), ( name: "Rose", product: "rose", stocklevel: "2", price: 4.99), ( name: "Peony", product: "peony", stocklevel: "0", price: 1.50), ( name: "Primula", product: "primula", stocklevel: "1", price: 3.12), ( name: "Snowdrop", product: "snowdrop", stocklevel: "15", price: 0.99), ];

The data is expressed as one or more JavaScript objects. The jQuery templating library provides a lot of flexibility in choosing the objects that can be used as data, but the format shown above matches the format of the data. JSON, is the most common. The JS0N format is very important because it is often used with Ajax.

In this example, the array consists of six objects, each with a set of properties that describe a specific product: display name, product name, number of units available, and price.

Template definition

As you can probably guess, the centerpiece of the template library is the data template. It is a set of HTML elements containing placeholders that correspond to various properties of data objects. The template for this example is shown below:

The first thing to notice is that the template is placed in a script element whose type attribute is set to a value of a non-existent type - text/x-jquery-tmpl. This is to prevent the browser from trying to interpret the content of the template as normal HTML markup. While not essential, this practice should be followed as it is extremely beneficial and will allow you to avoid a lot of potential problems in the future.

The second point I want to bring to your attention is that the id attribute is used to name the template defined on the script element. In this case, the template name is flowerTmpl. To apply a template to data, you need to know its name.

The template content will be applied to all objects in the dataset, resulting in a set of HTML elements for each object. You can see that the structure of the template as a whole corresponds to the set of elements that were used in previous articles to represent different types of flower products. The main difference between them is the code elements that perform the functions of placeholders (data placeholders) .

During template processing, each placeholder is replaced by the value of the property taken from the current object. For example, for the first array object, the placeholder $(product) will be substituted with the value of the product property, i.e. "astor". So part of the template

converted to the following HTML snippet:

Value substitution is not the only thing that templates can do. Other possibilities are discussed below.

Applying a template

To combine a template with data, use tmpl() method. In doing so, you specify the data to be used and the template to apply to it. An example of using this method is given below:

$("#flowerTmpl").tmpl(data).appendTo("#row1");

Here we select the element that contains the template using the $() function for this purpose, and call the tmpl() method on the result, passing it the data we want to process as an argument.

The tmpl() method returns a standard jQuery object that contains the elements retrieved from the template. In this case, this results in a set of div elements, each containing img, label, and input elements configured for one of the objects contained in the data array. To insert the entire set as a child of the row1 element, use the appendTo() method. The result is shown in the figure:

Result modification

The result is not entirely satisfactory, since all elements corresponding to different colors are displayed in one row. But since we are dealing with a jQuery object, positioning the elements the way we want is not a big deal. The example below shows how this can be done by influencing the result of the tmpl() method:

... $("#flowerTmpl").tmpl(data) .slice(0, 3).appendTo("#row1").end().end() .slice(3).appendTo("#row2" );

In this example, the slice() and end() methods are used to narrow and expand the set of selected elements, and the appendTo() method is used to add subsets of template-generated elements to different rows.

Note that to return the set to its original state before the slice() and appendTo() methods were applied, the end() method had to be called twice in a row. There's nothing illegal about this, and I'm happy to use the end() method to do what I need to do in one statement, but I don't like the end().end() sequence. In such cases, I prefer to break the entire sequence of actions into a number of separate operations, as shown in the example below:

Var templResult = $("#flowerTmpl").tmpl(data); templResult.slice(0, 3).appendTo("#row1"); templResult.slice(3).appendTo("#row2");

In both cases, the result will be the same: a presentation of a collection of products in two rows, each of which displays three types of colors, as shown in the figure:

Change how input is provided

Another possible approach is to change the way data is passed to the tmpl() method. The relevant example is shown below:

Vartemplate = $("#flowerTmpl"); template.tmpl(data.slice(0, 3)).appendTo("#row1"); template.tmpl(data.slice(3)).appendTo("#row2");

In this scenario, the distribution of elements in rows is done by using the template twice - once for each row. The corresponding part of the data objects is passed to the template each time using the slice() method. Despite the difference between this approach and the previous one, we get the same result that was presented in the figure above.

Expression evaluation

Data objects can be used for more than just getting property values. If you put a JavaScript expression between two curly braces, the template engine will evaluate it and insert it into the HTML generated by the template. The relevant example is shown below:

In this template, the input element's value attribute is set based on the value of the stocklevel property using a ternary conditional operator. An expression enclosed in curly braces plays the same role as an immediate property value written instead. If the value of the stocklevel property is greater than zero, then value is set to 1, otherwise it is set to 0.

The view of the resulting page in the browser window is shown in the figure below. A stocklevel value greater than zero is set for all colors except peonies:

This example illustrates the basic pattern of working with templates: data is combined with a template to get DOM objects, which are then added to the document using the core functionality of jQuery. You can use both directly given values ​​and calculated expressions to generate content.

Using Template Variables

Templates are not JavaScript. Any content you add to the script element is considered part of the template and will be included in the output. To make templates more flexible, you are provided with a small number of context variables that can be used in placeholder descriptors. A brief description of these variables is provided in the table below:

Using the $data Variable

The $data variable returns the current data element to which the template is applied. For example, the variable $data used will refer to each of the objects in turn, corresponding to individual types of flowers. The template used a ternary conditional operator to retrieve the data in the previous example. This approach is quite acceptable, however, reading the resulting templates often causes difficulties, which, of course, is desirable to avoid.

I always try to keep my template code to a minimum, so I prefer to use the $data variable inside JavaScript functions that I then call from the template. The relevant demo is shown below:

This example defines a stockDisplay() function that returns the value that should be displayed in the input element. The argument to this function is a data object, which we get inside the template using the $data variable. Considering that this is just a simple ternary operator, the difference in readability of the code compared to the previous version is not very significant, but in the case of more complex expressions or in the case of repeated use of an expression within the same template, it will be much more noticeable.

When defining the functions that will be called from the template, be careful. The point is that such functions must be defined before calling the tmpl() method. I always try to put them at the end of the script element, but if the function needs to be inside a ready event handler, then you should definitely make sure that it has been defined before. Another common mistake is that a function is often defined inside a template.

Using the $() function inside a template

You can use jQuery's $() function for placeholders within a template, but it's important to remember that template-generated elements are not attached to the document and therefore will not be included in jQuery's selection sets. I rarely use this feature because I'm usually more interested in elements and their associated data that I generate myself.

Using the $item Variable

The object returned by the $item variable does several things. The first is to allow additional data to be exchanged between the JavaScript script and the template. The relevant example is shown below:

In this example, we create an options object that defines a property (discount) and a method (stockDisplay()). This object is then passed to the tmpl() method as the second argument. Access to the properties and methods of the object from the template is provided by the $item variable. As you can see, to handle the discount in the price, the discount property of the options object is used here.

I want to draw your attention to the need to include the $ prefix in the names of context variables: $item and $data. The same prefix is ​​also required in the $(...) template descriptor construct used to substitute values ​​into the template. Omitting any of these prefixes is one of the most common mistakes.

We will talk about other uses of this object later.

Using Nested Templates

When creating complex applications, it sometimes makes sense to break a large template into several parts, which are combined already at the application execution stage. As will be shown later, this way of combining templates provides more flexible output control. We'll start with the most basic. The example below shows how one template can refer to another:

...

In this example, the template is split into two parts. The first one, the flowerTmpl template, is called for each element of the data array. In turn, this template calls the inputTmpl template to create input elements. The second template is called using the descriptor ((tmpl)). This call takes three arguments. The first two are the current item and the options object; these arguments are enclosed in parentheses. The third argument is the template to call. It can be set either with a jQuery selector (as done above), or with a variable or function defined in the script.

Using conditional templates

The template engine provides the ability to dynamically make decisions regarding the use of different parts of a template, depending on the fulfillment of certain conditions. This is what descriptors are for. ((if)) and ((/if)), an example of which is shown below:

... ((if stocklevel > 0))

.png"/>
((/if))

The condition is specified in the ((if)) descriptor, and the part of the template enclosed between this descriptor and the ((/if)) descriptor will only be used if the conditional evaluates to true. If this result is false, then the specified part of the template is ignored. In this case, the value of the stocklevel property is checked, and if it is zero, then the entire flowerTmpl template is ignored. This means that only those products that are in stock will be displayed, as shown in the figure:

More complex conditions can be specified using the descriptor ((else)), which allows you to specify the part of the template that should be used in cases where the result of evaluating the expression in the descriptor ((if)) is false. The relevant example is shown below:

... ((if stocklevel > 5))

.png"/>
((else stocklevel > 0))
.png"/>
((else))
.png" style="opacity:0.5"/>
((/if))

In this scenario, the set of items displayed is determined by how many items of a particular type of product are in stock: more than five, five, less than five, or not at all. I've only introduced minor differences between the elements generated for each of these conditions, but you can use these features to generate completely different content. Finally, other templates can be conditionally called if needed.

The result of the above script is shown in the figure:

With the release of jQuery, developers' lives have become much easier. For example, we can easily do the following:

$("#someElement").children().each(function() ( $(this).wrap($("

")); });

This code will put all children of the element with id #someElement into a tag

. There is nothing wrong with such operations; this expression is absolutely correct and is very convenient in some situations. But the HTML code placed in our script is a violation of the structural logic of the code. In this simple example, this violation is not significant, but in real projects it is very common. Typically, such code contains many HTML fragments that are built into the DOM after receiving data from AJAX requests. This style can quickly turn into something that is extremely unreadable.

Using templates will allow us to eliminate this shortcoming by separating HTML fragments from scripts, thus separating the logic of the content of different types of code. In the process, I can't help but show you some of the super cool AJAX innovations introduced by jQuery 1.5.

Start

In this example, we will be developing a Twitter widget that will load not only our most recent posts, but also a list of friends and followers. I chose Twitter for this example because it interacts with JSON data which is easy and fun to work with.

Let's get started; the widget itself will be built based on the following HTML structure:

jQuery, AJAX and Templating



In this example, we are using HTML5. To do this, we specified a simplified DOCTYPE and a meta element. You can also notice in the code the connection to style sheets, which will be described in a couple of minutes. In order to support the current version of IE8 and below, we use conditional comments on a special html5shiv plugin.

We use aside

Most likely, this widget will look like a sidebar, and display the content of the specified Twitter user. Given this, I decided to put the content in a tag


In the browser, this example would look like this:

Template caching

In every call $("#...").tmpl(...) the template is compiled, which, despite the sharp increase in the speed of JavaScript in modern browsers, can have an extremely negative impact on performance. Developers jQuery Templates could not ignore this obvious fact, therefore, in jQuery Templates a mechanism is provided for precompiling and caching templates.

The template is compiled and cached as follows:

$("#movieTmpl").template("movieTmpl");
The compiled template is stored in the internal cache jQuery Templates under the name movieTmpl. To access the cached template, use the method jQuery.tmpl(), and the name of the cached template is passed to it as the first parameter:

$.tmpl("movieTmpl", dataItems).appendTo("#movieListBag");
The example below navigates through a list of movies, using a cached template to display movie information.

The template code practically does not differ from those that I used earlier, its only difference is that links for navigation are additionally placed under the description of the movie (the complete code of the example is in the file CachedTemplates.htm):


The accompanying script is just as simple:

var movieIndex = 0; $(function () ( $("#movieTmpl").template("movieTmpl"); updateMovie(); $("#movieBag").delegate(".nav-link", "click", function () ( movieIndex += parseInt($(this).attr("x-inc")); updateMovie(); )); )); function updateMovie() ( $("#movieBag").empty(); $("#movieBag").append($.tmpl("movieTmpl", dataItems, ( canMoveBack: movieIndex > 0, canMoveFwd: movieIndex< dataItems.length - 1 })); }
The navigation link click handler changes the index of the selected movie and then calls the function updateMovie(), which first clears the movie description container and then fills it with new data.

Here is how this example looks in the browser:


The browser, of course, will download the corresponding file - but you still won't be able to access its contents.

But the template can still be placed in a separate file, and this will require literally one additional line of code (the complete example code is in the file):

$(function () ( $.get("Templates/DynamicLoading.htm", (), function (templateBody) ( $.tmpl(templateBody, dataItems).appendTo("#movieListBag"); )); ));
Because in this case, we get the template in the form of text, the method is used to instantiate it jQuery.tmpl(), whose first argument is the received template text.

yes method jQuery.tmpl() used to instantiate both cached templates by name and templates given as text (tradition!..) - however, it is smart enough to distinguish them from each other.

If you need to load multiple related templates, you can use the library WaitSync(see "Synchronization of asynchronous calls. WaitSync") or write your own synchronizer (the complete code of the example is in the file):

$(function () ( var ws = new WaitSync(function () ( $.tmpl("movieTmpl", dataItems).appendTo("#movieListBag"); )); $.ajax(( cache: false, url: " Templates/MovieTmpl.htm", success: ws.wrap("MovieTmpl", function (templateBody) ( $.template("movieTmpl", templateBody); )), error: ws.wrap("MovieTmpl", function () ( alert("Error loading MovieTmpl.htm!"); )) )); $.ajax(( cache: false, url: "Templates/ActorsTmpl.htm", success: ws.wrap("ActorsTmpl", function (templateBody) ( $.template("actorsTmpl", templateBody); )), error: ws.wrap("ActorsTmpl", function () ( alert("Error loading ActorsTmpl.htm!"); )) )); ));
Note that in this case the template actorsTmpl called by name (file Templates\MovieTmpl.htm):

Director: $(director)
Cast: ((tmpl(actors, ( last: actors )) "actorsTmpl"))
Year: $(year)

Dynamic update

In the last section of the practical part, I will show two more work scenarios. jQuery Templates- changing the associated data and replacing the associated template.

In the example below, for each movie, the ability to change its rating has been added (the complete code of the example is in the file DynamicUpdate1.htm):


Related code:

$(function () ( $("#movieTmpl").tmpl(dataItems).appendTo("#movieListBag"); $("#movieListBag").delegate(".rating-button", "click", function ( ) ( var item = $.tmplItem(this); item.data.rating += parseInt($(this).attr("x-inc")); item.update(); )); ));
As you can see, this code is very similar to the bookmark code from the "Transformation" section, only when working with bookmarks, I accessed a shared object viewState, and here I'm working with the data associated with the template instance.

In the browser, this example looks like this:

The following example demonstrates the substitution of the associated template (the complete example code is in the file DynamicUpdate2.htm):


Here I am using two templates, movieShortTmpl and movieFullTmpl, the common part of which is placed in the template movieMainTmpl.

Related code:

$(function () ( var shortTemplate = $("#movieShortTmpl").template("shortTemplate"); var fullTemplate = $("#movieFullTmpl").template(); $.tmpl("shortTemplate", dataItems). appendTo("#movieListBag"); $("#movieListBag").delegate(".more-details", "click", function () ( var item = $.tmplItem(this); item.tmpl = item.tmpl === shortTemplate ?fullTemplate: shortTemplate;item.update();));));
I think this code needs more explanation.

To replace the template, I need a link to the compiled template. I get these links with calls .template(). In addition, because sample shortTemplate is used to render the list of movies after the page has loaded, I store it in a cache so I can instantiate it by name.

In the browser, this example looks like this:

Conclusion

The code for the examples used in the article can be downloaded from this link.

Download jQuery Templates you can from the ASP.NET CDN website or directly from the GitHub repository:
Brian Landau Benchmarking Javascript Templating Libraries.

In conclusion, I would like to express my gratitude to Vitaly Dilmukhametov and Denis Gladkikh for valuable comments made during the work on the article.

Tags: Add tags