Welcome to a blog on getting the data from a list and putting the data in a template. Here, we will discuss a step by step procedure to get the data from a list and place it in a template
Here, the main code to get the data from a list in detail is given below.
- var requestUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/GetByTitle ('list name')/Items";
-
-
- $.ajax({
- url: requestUrl,
- type: "GET",
- async: false,
- headers: { "Accept": "application/json; odata=verbose" },
- success: function (data) {
-
-
- $.each(data.d.results, function (index, item) {
-
- $("#empTemplate").tmpl(item).appendto("#tbDetails");
- });
- },
- error: function (data) {
- console.log (data);
- alert("error " + data)
- }
- })
In the code given above, we are using a data template with an id “empTemplate” and a table template with an id “tbDetails”. Now, we will create the Data template and table Template, which are given below.
Here is the main code to create the Data template.
- <script id="empTemplate" type="text/x-jQuery-tmpl">
- <tr>
- <td>${EmployeeId}</td>
- <td>${EmployeeName}</td>
- <td>${EmployeeDepartment}</td>
- </tr>
- </script>
Here is the main code to create the Table template
- <table id="tbDetails" cellpadding="0" cellspacing="0" >
- <thead style="background-color:#DC5807; color:White; font-weight:bold">
- <th>Employee Id</th>
- <th>Employee Name</th>
- <th>Employee Department</th>
- <tr style="border:solid 1px #000000">
- </tr>
- </thead>
- <tbody>
- </tbody>
- </table>
Now, we will create a container(div) to bind the Data template and Table template
- <div id="empContainer"></div>
Now, we are applying styles for the table element with the code given below.
- <style type="text/css">
- table,th,td
- {
- border:1px solid black;
- border-collapse:collapse;
- }
- </style>