Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use templates with jQuery without additional plugins?

Tags:

jquery

I have the method below that queries my server via ajax, JSON data is returned, and I loop through the data and write out to html.

The code works, but it is messy and inefficient. Is there a way to put the html in a template of sorts, instead of writing it out in my javascript code?

Thanks

 $("[name=btnSearch]").on("click", function () {   
   $.getJSON(ajaxMethod + searchTerm, function (data) {
        var html = "";
        var sel = "";
        var name = "";
        var type = "";
        //alert(id);
        var css = "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only";
        $.each(data, function (key, val) {
                sel = val.ID;
                name = val.DisplayName;
                type = "user";
            html += '<tr data-type = "' + type + '" data-result-title = "' + name + '" data-result-id="' + sel + '">';
            html += '<td id="' + sel + '">' + name + '</td>';
            html += '<td><input type="button" class="select" value="select" style="' + css + '"></td>';
            html += '</tr>';
        });
        //html += '<tr><td style="padding-top: 4px;">&nbsp;</td><td style="padding-top: 4px;"><input id="btnAddMembers" type="button" value="Add Members" /></td></tr>';
        $(html).appendTo('[name=' + div + ']');
    });
 });
like image 257
SkyeBoniwell Avatar asked Jul 26 '13 14:07

SkyeBoniwell


3 Answers

This question does basically what you're looking for (without a plugin, but by adding an additional method to the prototype object).

Read the accepted answer here: Recommended jQuery templates for 2012?

A basic JSFiddle is here: CLICK

Very simple, and easy to edit and extend, the JSfiddle should give you a good idea of how it works.


The Code:

HTML:

<script type="text/template" id="cardTemplate">
<div>
    <a href="{0}">{1}</a>
</div>
</script>

<div id="container"></div>

JS:

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};

var cardTemplate = $("#cardTemplate").html();
var template = cardTemplate.format("http://example.com", "Link Title");
$("#container").append(template);
like image 199
Anil Avatar answered Oct 06 '22 01:10

Anil


You can use one of jquery/js template engines jquery template, jsRender, dust.js. There are a a lot of them.

like image 34
YD1m Avatar answered Oct 06 '22 01:10

YD1m


Why don't you use some knockout?

Here's a jsFiddle with an example.

HTML

<input id="searchBtn" type="button" value="Search" data-bind="click: SearchItems" />
<table data-bind="foreach: Items">
    <tr data-type="user" data-bind="attr: { 'data-result-title':DisplayName(), 'data-result-id':Id() }">
        <td data-bind="text: DisplayName()"></td>
        <td>
            <input type="button" class="select" value="select" style="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />
        </td>
    </tr>
</table>

Javascript

var id = 0;

function Item(id, name) {
    var self = this;
    self.Id = ko.observable(id);
    self.DisplayName = ko.observable(name);
}

function ItemsModel() {
    var self = this;
    self.Items = ko.observableArray([]);
    self.SearchItems = function () {
        self.Items.push(new Item(id++, 'Some Name ' + id));
    }
}

$(function () {
    ko.applyBindings(new ItemsModel());
});
like image 41
sergioadh Avatar answered Oct 06 '22 00:10

sergioadh