Official jQuery plugins: Templates plugin. Learning to work with jQuery templates Layout of digital data in jquery

On October 4, 2010, the announcement of three jQuery plugins, created with the support of the Microsoft team, was published. These plugins—the jQuery Templates plugin, the jQuery Data Link plugin, and the jQuery Globalization plugin—are designated as “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. The data binding plugin is needed to link objects with 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 a page in accordance with the format of the current language.

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

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

jQuery Templates plugin

Let's start with a simple example:

  • $(Name) ($(ReleaseYear))
  • var movies = [ ( Name: "The Red Violin", ReleaseYear: "1998"), ( Name: "Eyes Wide Shut", ReleaseYear: "1999"), ( Name: "The Inheritance", ReleaseYear: "1976") ]; $("#movieTemplate").tmpl(movies) .appendTo("#movieList");

    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 running, we will get the following markup:

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

    And now to the essence of the question.
    What does the plugin do?
    The plugin receives as input a template string and a set of objects (or one object) that need to be output to a string (or markup) with formatting.
    Where is this applied?
    This plugin is mainly useful for dynamically displaying JS objects on the page, the objects can be obtained in the most in different ways, for example, during calculations or based on the results 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 contents of the first selected element and uses it as a template for formatted output of the specified data.
    data– data to be output to a template (object or array of objects).
    options– optional, user-defined extension in the form of key-value pairs for the output object in the template.
    jQuery.tmpl(template, [ data ], [ options ])
    Uses the specified template to produce formatted output of the specified data.
    template– a template for formatting data, 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 a structure (object) for the first selected element with the results of the template engine. The object returned by the method provides access to:

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

    This method is used, for example, when, after formatting the data, you need 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 in jQuery wrapper).
    .template([ name ])
    The method makes a compiled version of the formatting template from the contents of the first selected element.
    name– optional template name, if the name is specified, then you can use it to access this template in a method jQuery.tmpl(name, data, options)
    jQuery.template([ name, ] template)
    The method is similar to that described above, only here the template is passed as a parameter template– this can be a string, a string with markup, an HTML element (including in a jQuery wrapper).

    Template syntax

    I will briefly describe several 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)"– will insert the value of the obj.Name field into the template, and given 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, ‘ – ‘))”– will insert the result of this method into the template.
    ((html fieldNameOrExpression))
    The template element $(field) (or ((= field))) inserts the value of the specified field as text into the result, i.e. If there are HTML tags in the string, they will be encoded rather than 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)) .
    To get started with the plugin, I’ve already said enough about it, I can only add that the template syntax allows you to insert nested templates, conditional instructions, access some JS and jQuery objects and something else... The rest is material for a future article.

    Sources

    The article was written based on materials found on the World Wide Web. This is mainly a translation of official documentation. The originals can be viewed at the following links:

    • (examples taken from there)
    About the author

    My name is Andrey Zaitsev, profile on the zandroid forum

    This is my first article on this blog, I hope, and not the last. Many thanks to Gennady for the opportunity to publish and for useful tips on writing and designing material.

    Examples

    Example 1: Dynamically switching the applied template

    table ( cursor:pointer; border-collapse:collapse; border:2px solid blue; width:300px; margin:8px; ) table tr ( border:1px solid blue; color:blue; background-color:#f8f8f8; ) table td ( padding:3px; ) table tr:hover ( color:red; ) .movieDetail ( background-color:yellow; ) .movieDetail.row1 ( border-bottom:none; ) .movieDetail.row2 ( border-top:none; ) $(Name) $(Name)$(ReleaseYear)Director: $(Director) Click for details:

    var movies = [ ( Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" ), ( Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" ), ( Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" ) ]; var selectedItem = null; /* Render the summaryTemplate with the "movies" data */ $("#summaryTemplate").tmpl(movies).appendTo("#movieList"); /* Add onclick handlers for movie template items using the summary or details template */ $("#movieList") .delegate(".movieSummary", "click", function () ( if (selectedItem) ( // Set the template on the previously selected item // back to the summary template selectedItem.tmpl = $("#summaryTemplate").template(); selectedItem.update(); /* Get the data structure for the template item which this clicked element belongs to, and make it the selected item */ selectedItem = $.tmplItem(this); /* Set the template on this item to the detail template */ selectedItem.tmpl = $("#detailTemplate").template(); .update(); )).delegate(".movieDetail", "click", function () ( /* Set the template on this item to the summary template */ selectedItem.tmpl = $("#summaryTemplate").template (); selectedItem.update(); selectedItem = null);

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

    Example 2: Inserting data with markup into a template

    .role (font-weight:bold;font-style: italic;) #movieContainer (padding-left: 8px;) $(Name)

    ((html Synopsis))

    /* The Synopsis data field contains HTML markup. */ var movie = ( Name: "Meet Joe Black", Synopsis: "The grim reaper (Brad Pitt) visits Bill Parrish (Anthony Hopkins)..." ); /* Render the template with the movie data. The template uses the ((html)) template tag to insert the Synopsis HTML markup data. */ $("#movieTemplate").tmpl(movie) .appendTo("#movieContainer");

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

    P.S.

    I didn’t describe the examples, but if the audience supports my initiatives, 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.

    With the release of jQuery, life has become much easier for developers. For example, we can easily do the following:

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

    This code will put all descendants of the element with id #someElement into the 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 it is very common in real projects. 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 drawback by separating HTML fragments from scripts, thus separating the content logic different types code. Along the way, I can't help but show you some super cool AJAX new features 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 that 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 Dan Wellman

    Husband, father, front-end developer and author. Writes for Nettuts and Packt Publishing. Works for @designhaus | jQuery fanatic

    • Tweets
    • Friends
    • Followers
    This widget has super-awesome features which require the use of JavaScript. Please enable it for a better internet experience

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

    Using aside

    Most likely, this widget will look like a sidebar and display the content of the specified Twitter user. With this in mind, I decided to put the content in a . In order to easily access this element, we will set an ID for it.

    Speaking of markings. All of the Twitter user's post titles will be included in the tag, and the image and everything else will be included in the tag.

    You can change this to your own preference when you remodel this example. We could get all the required data via JSON, which we will do, however, if there is a delay in the loading process, the visitor will be shown a lot of empty blocks. So it’s better for us to wait until the download is complete and then fill the blocks.

    We will also have tabs on our page for switching between lists of messages, friends and subscribers. All of them will be enclosed in tags

    
    Top