{"id":888,"date":"2017-05-30T15:50:58","date_gmt":"2017-05-30T10:20:58","guid":{"rendered":"https:\/\/blog.binarybits.net\/?p=888"},"modified":"2017-05-30T15:52:39","modified_gmt":"2017-05-30T10:22:39","slug":"display-attachments-using-jslink-in-sharepoint","status":"publish","type":"post","link":"https:\/\/blog.binarybits.net\/display-attachments-using-jslink-in-sharepoint\/","title":{"rendered":"Display attachments using JSLink in SharePoint"},"content":{"rendered":"
Recently I had a requirement where the customer wanted to show the actual attachment’s URL in the list view instead of default Icon. Following JSLink code will help to do that.<\/p>\n
(function () {\r\n var linkFiledContext = {};\r\n linkFiledContext.Templates = {};\r\n linkFiledContext.Templates.Fields = {\r\n \"Attachments\": { \"View\": OverrideAttachmentFieldRendering }\r\n };\r\n SPClientTemplates.TemplateManager.RegisterTemplateOverrides(linkFiledContext);\r\n})();\r\n\r\nfunction OverrideAttachmentFieldRendering(ctx) {\r\n var itemId = ctx.CurrentItem.ID;\r\n var listName = ctx.ListTitle;\r\n return GetAttachments(listName, itemId);\r\n}\r\n\r\nfunction GetAttachments(listName, itemId) {\r\n var url = _spPageContextInfo.webAbsoluteUrl;\r\n var requestUri = url + \"\/_api\/web\/lists\/getbytitle('\" + listName + \"')\/items(\" + itemId + \")\/AttachmentFiles\";\r\n var htmlString = \"<span style='white-space: nowrap;'>No attachment(s)<\/span>\";\r\n\r\n $.ajax({\r\n url: requestUri,\r\n type: \"GET\",\r\n headers: { \"ACCEPT\": \"application\/json;odata=verbose\" },\r\n async: false,\r\n success: function (data) {\r\n for (var i = 0; i < data.d.results.length; i++) {\r\n htmlString += \"<a style='white-space: nowrap;' href='\" + data.d.results[i].ServerRelativeUrl + \"'>\" + data.d.results[i].FileName + \"<\/a>\";\r\n if (i != data.d.results.length - 1) {\r\n htmlString += \"<br\/>\";\r\n }\r\n }\r\n },\r\n error: function (error) {\r\n console.log(\"An error occured while fetching attachment details. Details: \" + JSON.stringify(error))\r\n }\r\n });\r\n\r\n return htmlString;\r\n}<\/pre>\n