I wish to display a popup when the user hovers over a particular link.
To do so, I first request the particular JSON data from the server via Ajax.
The server queries the DB, and escapes any data which happens to be user provided using htmlspecialchars(), and echos json_encode($data).
The client then assembles the HTML using the below template.
The client then displays the popup.
My question only relates to rendering the template.
Is there a better approach which will provide one or all of the following benefits?
- Templates are more readable.
- Templates are easier to maintain.
- Templates can be extended.
- Custom methods to display phone numbers, etc need not be created.
- Site is safer from an XSS respective.
- htmlspecialchars escaping is moved from the server to the client.
- Other benefits which I have not even thought of?
Thank you
function getTemplate(type,json) {
switch(type) {
case 'person':
return '<dl><dt>Name:</dt><dd>'+((d.firstname&&json.lastname)?json.firstname+' '+json.lastname:((json.firstname)?json.firstname:json.lastname))+'</dd>'
+'<dt>Account:</dt><dd>'+json.account_name+'</dd>'
+((json.title)?'<dt>Title:</dt><dd>'+json.title+'</dd>':'')
+'<dt>User Name:</dt><dd>'+json.username+'</dd>'
+'<dt>Password:</dt><dd>'+json.password+'</dd>'
+'<dt>Communication Method:</dt><dd>'+json.communication_method+'</dd>'
+((json.email)?'<dt>Email:</dt><dd>'+json.email+'</dd>':'')
+((json.account_phone)?'<dt>Account Phone:</dt><dd>'+ayb.display_phone(json.account_phone)+'</dd>':'')
+((json.phone)?'<dt>Direct Phone:</dt><dd>'+ayb.display_phone(json.phone)+'</dd>':'')
+((json.mobile_phone)?'<dt>Mobile Phone:</dt><dd>'+ayb.display_phone(json.mobile_phone)+'</dd>':'')
+((json.account_fax)?'<dt>Account Fax:</dt><dd>'+ayb.display_phone(json.account_fax)+'</dd>':'')
+((json.fax)?'<dt>Direct Fax:</dt><dd>'+ayb.display_phone(json.fax)+'</dd>':'')
+((json.address || json.location)?'<dt>Address:</dt><dd>'+json.address+((json.address && json.location)?'<br>':'')+json.location+'</dd>':'')
+'</dl>';
break;
case 'company':
return 'bla bla bla';
break;
case 'somethingElse':
return 'bla bla bla';
break;
return '<h1>Invalid Template</h1>';
}
}