reading template {{VAR}} in node js [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
Improve this question
I'm making a custom function to make api calls based on the data user has sent in the form of a template.
for Example user send the below data:
body = {
userEmail: {{email}},
userName: {{name}},
userAge: {{age}}
}
and below is the data set where I have to create the mapping
data = {
email:"abc#xyz.com",
name:"Foo",
age:30
}
Any hint or suggestion where to start from will be really appreciated.

It can be done by using handlebars.
Below are a sample code snippet on how to render and replace the variable of a HTML Template file.
//nodeJS
const handlebars = require("handlebars");
const fs = require("fs");
const path = require("path");
const filePath = path.join(__dirname, "yourHTMLtemplate.html");
const source = fs.readFileSync(filePath, "utf-8").toString();
const template = handlebars.compile(source);
response.status(200).send(template({
user_Name: "Jack",
user_Age: "24",
user_Gender: "Male"
})
);
<table>
<tr>
<td>Name</td>
<td>{{{user_Name}}}</td>
</tr>
<tr>
<td>Age</td>
<td>{{{user_Age}}}</td>
</tr>
<tr>
<td>Gender</td>
<td>{{{user_Gender}}}</td>
</tr>
</table>
Your Output will be:
<table>
<tr>
<td>Name</td>
<td>Jack</td>
</tr>
<tr>
<td>Age</td>
<td>24</td>
</tr>
<tr>
<td>Gender</td>
<td>Male</td>
</tr>
</table>

Related

how to loop a nested array object in javascript with jquery

Hey im working on a project and i can't seem to get the hang of this. I want to loop through my nested array object "products" so that i can display it all and not just the last index.
// jquery getting our json order data from firebase
$.get("http://localhost:8888/orderslist", (data) => {
// i is for the index of the array of orders
let i = 0;
//for each loop through our array list
$.each(data, function () {
//console.log(data)
//console.log(i);
// is how we arrange the data and show it to the frontpage
$(`<table id = order_table_layout>
<tr>
<th>Customer</th>
<th>Date</th>
<th>Time</th>
<th>Total</th>
<th>Order</th>
<th>Order Status</th>
</tr>
<tr>
<td>${data[i].customer_name}</td>
<td>${data[i].date}</td>
<td>${data[i].time}</td>
<td>${data[i].total} Kr.</td>
<td>
${data[i].products[i].name}
${data[i].products[i].price} Kr.
</td>
<td>
</td>
</tr>
</table>`
).appendTo("#frontpage_new_ordertable");
// counts 1 up for each loop to go through list
i++;
//console.log(i);
});
});
Edit:
An example of the json data I'm working with look like this:
[
{
id: "4WQITi6aXvQJsKilBMns",
customer_name: "Susanne",
date: "22-12-2002",
time: "12:43:19",
total: 222,
products: [
{ name: "product name", price: 100 },
{ name: "product name2", price: 20 }
]
There's a couple of issues in your code. Firstly you're creating a brand new table for every object in the data array. It makes far more sense to instead create a new row in the table for each item.
Also, it appears that you want to loop through the child products array. As such you need an inner loop to create the HTML string for those elements outside of the template literal.
However it's worth noting that it's not good practice to have that much HTML in your JS. A better approach is to have a hidden template tr in your HTML which you can clone, update with the data from the data array, then append to the DOM in the tbody of the table.
With that said, try this:
//$.get("http://localhost:8888/orderslist", (data) => {
// mock response:
let data = [{id:"4WQITi6aXvQJsKilBMns",customer_name:"Susanne",date:"22-12-2002",time:"12:43:19",total:222,products:[{name:"product name",price:100},{name:"product name2",price:20}]},{id:"asjdkjk21ijjjew",customer_name:"Foo Bar",date:"10-05-2020",time:"16:46:16",total:68,products:[{name:"Lorem ipsum",price:50},{name:"Fizz buzz",price:18}]}];
let rows = data.map(item => {
let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
$clone.find('.customer-name').text(item.customer_name);
$clone.find('.date').text(item.date);
$clone.find('.time').text(item.time);
$clone.find('.total').text(item.total + ' Kr.');
let products = item.products.map(prod => `${prod.name}: ${prod.price} Kr.`);
$clone.find('.products').html(products.join('<br />'));
return $clone;
});
$("#frontpage_new_ordertable tbody").append(rows);
//});
tfoot {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="frontpage_new_ordertable">
<tbody>
<tr>
<th>Customer</th>
<th>Date</th>
<th>Time</th>
<th>Total</th>
<th>Order</th>
<th>Order Status</th>
</tr>
</tbody>
<tfoot>
<tr>
<td class="customer-name"></td>
<td class="date"></td>
<td class="time"></td>
<td class="total"></td>
<td class="products"></td>
<td></td>
</tr>
</tfoot>
</table>
<td>${data[i].total} Kr.</td>
<td>
${data[i].products[i].name}
${data[i].products[i].price} Kr.
maybe that's what's wrong?
is the number of the order similar to the number of product in products array?

How to Inject HTML using JavaScript

Solution
My question was asked with little knowledge in HTML and JavaScript, I apologize for this. With more experience I can clearly see that this was not a good question asked, anyway the solution to my own question can be found here:
best way to inject html using javascript.
Problem:
I am trying to show the whole list in HTML. For instance, if there are three names, I want the names to be shown in between <td>...</td>. Is there a way I can extract all this list to HTML via JavaScript?
I know I need an array and probably a for loop. Maybe I am thinking too complex.
Here is the HTML code:
<table class = "table table-striped">
<thead>
<tr>
<th>Full Name</th>
</tr>
</thead>
<tbody>
<tr id = "scoreList">
<tr>....</tr>
</tr>
</tbody>
</table>
Here is the JavaScript code:
// Loop through customers
for( var i = 0; i < keys.length; i++){
var k = keys[i];
// var id = customers[k].id;
var name = customers[k].name;
// Add code here to show list of names in html
}
Assuming that you use no frameworks, that's one easy way to do it:
// Generate the <td>'s.
const rendered = keys.map((v) => `<td>${v}</td>`).join('');
// Write them on the screen.
document.getElementById('scoreList').getElementsByTag('tr')[0].innerHTML = rendered;
With pure javascript (and assuming you'll want the <td> elements in <tr> elements) you can use this.
var customers = [
{
firstName: 'John',
lastName: 'Smith'
},
{
firstName: 'William',
lastName: 'Shakespear'
}
]
for(var customer of customers) {
var tdFN = document.createElement('TD');
tdFN.innerHTML = customer.firstName;
var tdLN = document.createElement('TD');
tdLN.innerHTML = customer.lastName;
var tr = document.createElement('TR');
tr.appendChild(tdFN);
tr.appendChild(tdLN);
document.querySelector('table.table.table-striped tbody').appendChild(tr);
}
<table class="table table-striped">
<thead>
<tr>
<th>Full Name</th>
</tr>
</thead>
<tbody>
<tr id="scoreList">
</tr>
</tbody>
</table>

Rendering DB values using Javascript

Till date in a project of mine there has been straight forward implementation of DB normalization and the way "status codes" are stored , for example
Patient_table
patientId | referralStatus
1001 1
1002 2
Referral_status_codes_master
refStatusCode | refValue
1 Pending
2 Awaiting
Joining these two tables gives appropriate data for "STATUS_CODES" .
My intent here is , would it be appropriate if i use Javascript to achieve this for relatively small Master table values , i.e which don't change at all , like status here for example .
let's say i load patient data in a HTML table as it is and by using javascript i change their meanings .
<tr>
<td>1001</td>
<td>1</td>
</tr>
Objective : Intead of using join in sql query , obtain same results using Javascript on client side.
and i bind that HTML table to a JS function and change status 1 to "Pending", i know it's possible ,my Question is :
What are the disadvantages of doing it .
Are there any Libraries already existing for this very purpose only.
Please provide your suggestions .
Thank you
Since you have finite number of statuses, you can map values to user friendly name and than just replace them using js/jQuery
var statusMap = {
'1': 'Normal',
'2': 'Missing',
'3': 'Dead',
};
$(document).ready(function () {
$('[data-status]').each(function () {
$(this).html(statusMap[$(this).data('status')]);
})
});
table {
width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
<tr>
<td>John Wick</td>
<td data-status="2"></td>
</tr>
<tr>
<td>Abraham Lincoln</td>
<td data-status="3"></td>
</tr>
<tr>
<td>Dummy User</td>
<td data-status="2"></td>
</tr>
</table>
statusMap can be generated from PHP side by doing json_encode({All values from Referral_status_codes_master});

Merging duplicated rows in JSP table

I'm trying to generate a HTML table from an input Excel sheet using Apache POI in a JSP page. I have managed to code the part where the data is fetched from Excel and displayed as a HTML table, but the problem is some of the primary IDs has been duplicated in severals rows but they have different values in other rows. Example (2 Johns with Different Lastname):
<table>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>John</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
The code to generate the table :
out.println("<table>");
while (rowIter.hasNext())
{
row =(HSSFRow)rowIter.next();
input_fname = row.getCell(0);
input_lname = row.getCell(1);
input_age = row.getCell(2);
fname = input_fname.getRichStringCellValue().getString();
lname = input_lname.getRichStringCellValue().getString();
age = input_age.getRichStringCellValue().getString();
out.println("<tr>");
out.println("<td>"+fname+"</td>");
out.println("<td>"+lname+"</td>");
out.println("<td>"+age+"</td>");
out.println("</tr>");
}
}
out.println("</table>");
Please anyone advise me how can I merge the duplicated rows according to the Primary ID, First Name as below :
<table>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td rowspan="2">John</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>Doe</td>
<td>80</td>
</tr>
</table>
I have tried searching for similar question but i couldn't find any solution for my problem and I'm quite a beginner in Javascript and JQuery (maybe that's the problem). Any suggestions is much appreciated. Thanks in advance!
You are asking the wrong question. Wouldn't it be much easier to write the HTML correctly in the first place rather than try to do some merge on the HTML?
Thus, loop over the entries and put them in some suitable datastructure e.g. a Map keyed by fname and with a list as the value. Person class is a simple bean to hold the data.
Map<String, List<Person>> people = new TreeMap<String, List<Person>> ();
while (rowIter.hasNext())
{
row =(HSSFRow)rowIter.next();
input_fname = row.getCell(0);
input_lname = row.getCell(1);
input_age = row.getCell(2);
fname = input_fname.getRichStringCellValue().getString();
lname = input_lname.getRichStringCellValue().getString();
age = input_age.getRichStringCellValue().getString();
Person person = new Person(fname, lname, age);
if(! people.containsKey(person.fname)){
people.put(person.fname, new ArrayList<Person>());
}
people.get(person.fname).add(person);
}
}
Then loop over this data structure and write the HTML:
for(String key : people.keySet()){
List<Person> persons = people.get(key));
int rowSpan = persons.size();
//write the HTML accordingly.
}
You can:
add a class when printing the name in your back-end code e.g. out.println("<td class="fname">"+fname+"</td>");
and then with jQuery
var last_selected_name = "";
/* Get all the first names cells */
jQuery('td.fname').each(function(i,obj){
current_name = jQuery(obj).text();
/* check for repeated names */
if (current_name == last_selected_name)
{
jQuery("td.fname:contains('"+current_name+"')").each(function(index,object){
if (index == 0)
{
/* check if already has rowspan attribtue */
row_span = jQuery(object).attr('rowspan')?jQuery(object).attr('rowspan'):1;
/* add one */
row_span++;
/* include the new rowspan number */
jQuery(object).attr('rowspan',row_span)
}
else
{
/* delete the other first name cells */
jQuery(object).remove();
}
})
}
last_selected_name = current_name;
})

Convert HTML table to array [duplicate]

This question already has answers here:
Convert html table to array in javascript
(5 answers)
Closed 7 years ago.
I have a html table
<table>
<tr>
<th>Type</th>
<th>Text</th>
<th>Time</th>
<th>Notification Time</th>
</tr>
<tr>
<td>Lab1</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Monday, Wednessday</td>
</tr>
<tr>
<td>Lab2</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Tuesday, Wednessday</td>
</tr>
</table>
Now I want to use those values of <td> and form an array in php or jquery.
Any idea how to do it in the most simplest way?
In jquery:
var tdCollection = $("table").find("td");
var array = [];
$.each(tdCollection, function(key, el){
array.push($(el).text());
});
console.log(array);
fiddle: http://jsfiddle.net/qqdwct7h/
But it would be better to set an id attribute for the table, beacuse using $(table) isn`t best way to select a certain table.
Check this jQuery traversing and Ajax sample :)
<script type="text/javascript">
var tableRows = $("table tr"),
currentRow,
tableData = [];
for (var i = tableRows.length; i--;) {
currentRow = $(tableRows[i]);
tableData.push({
field1: $(":nth-child(1)", currentRow),
field2: $(":nth-child(2)", currentRow),
field3: $(":nth-child(3)", currentRow),
field4: $(":nth-child(4)", currentRow)
});
}
//Sample Test to verify if data is fetched
console.log(tableData);
$.ajax({
url: "sample-ajax-handler.php",
type: "POST",
data: tableData,
success: function (e) {
//do what you want here :)
}
});
</script>
I wrote a fiddle that allows to generate an array based on the column:
http://jsfiddle.net/5vfm6k6q/2/
Works like this:
var parser = new ArrayParser(),
result = parser.getArray('#table', 'Type'); // table selector, column

Categories

Resources