none
Show Attachments with JSLink

    Question

  • Hello,

    I have created a custom list view, with JSLink, for announcements list which I use it as FAQ view.

    My problem is that I can't show attachments link.

    I tried to implement it like in DispForm.aspx but no luck.

    Javascript code:

    (function () { var accordionContext = {}; accordionContext.Templates = {}; accordionContext.OnPostRender = accordionOnPostRender; accordionContext.Templates.Item = accordionTemplate; SPClientTemplates.TemplateManager.RegisterTemplateOverrides(accordionContext); })(); function accordionTemplate(ctx) { var title = ctx.CurrentItem["Title"]; var description = ctx.CurrentItem["Body"]; var attachments = ctx.CurrentItem["Attachments"]; // Return whole item html return "<tr>" + "<td colspan='13'>" + "<h2 class='heading' style='margin-bottom:0; font-size:16px;color:#2887dc'>" + title + "</h2>" + "<div class='content' style='white-space: -moz-pre-wrap;'>" + description + "<table><tr id='idAttachmentsRow' style='display: table-row;'>"+ "<td class='ms-formbody' id='SPFieldAttachments'><table border='0' cellpadding='0' cellspacing='0' id='idAttachmentsTable'><tr><td><span>" + attachments + "</span></td></tr></table></td>" + "</tr></table>" + "</div>" + "</td>" + "</tr>"; } function accordionOnPostRender() {

    // if (typeof ShowAttachmentRows == "function") ShowAttachmentRows(); $(".content").hide(); //toggle the componenet with class msg_body $(".heading").click(function () { $(this).next(".content").slideToggle(500); }); $('.heading').css('cursor', 'pointer'); }


    Is there any way you can show attachments in custom List View like in DispForm.aspx?

    Thanks in advance

    Giorgos


    • Edited by geo82 Friday, July 11, 2014 1:49 PM
    Friday, July 11, 2014 1:42 PM

Answers

  • Hi,

    We can use jQuery and JSLink to achieve it.

    The following code for your reference:

    (function () {
    
        // Create object that have the context information about the field that we want to change it output render  
    
        var linkFiledContext = {};
    
        linkFiledContext.Templates = {};
    
        linkFiledContext.Templates.Fields = {
             
            "Attachments": { "View": AttachmentsFiledTemplate }
        };
    
        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(linkFiledContext);
    
    })();
    
    
    // This function provides the rendering logic for list view 
    function AttachmentsFiledTemplate(ctx) {
        var itemId = ctx.CurrentItem.ID;
        var listName = ctx.ListTitle;       
        return getAttachments(listName, itemId);
    }
    
    function getAttachments(listName,itemId) {
      
        var url = _spPageContextInfo.webAbsoluteUrl;
        var requestUri = url + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")/AttachmentFiles";
        var str = "";
        // execute AJAX request
        $.ajax({
            url: requestUri,
            type: "GET",
            headers: { "ACCEPT": "application/json;odata=verbose" },
            async: false,
            success: function (data) {
                for (var i = 0; i < data.d.results.length; i++) {
                    str += "<a href='" + data.d.results[i].ServerRelativeUrl + "'>" + data.d.results[i].FileName + "</a>";
                    if (i != data.d.results.length - 1) {
                        str += "<br/>";
                    }                
                }          
            },
            error: function (err) {
                //alert(err);
            }
        });
        return str;
    }
    

    Save the code above as a js file, then add the js file and jQuery js lib into a document library.

    JSLink refer: ~site/DocumentLib/jquery-1.11.1.min.js|~site/DocumentLib/jslink.js

    Best Regards


    Dennis Guo
    TechNet Community Support

    • Marked as answer by geo82 Thursday, July 17, 2014 9:27 AM
    Thursday, July 17, 2014 1:55 AM
    Moderator

All replies

  • Hi,

    You can use XSLT source and append document with <a href=""> tag to have link.

    Thanks,

    Kirti P.

    Friday, July 11, 2014 2:39 PM
  • The Attachments column of a list contains the link to the attachment file.

    Since the view framework already allows including a column with the link, I'm guessing that you wish to show the atual contents of the attachment. In that case, your javascript would need to ready the bytes of the file (an ajax request) and then HTMLEncode the response to show in your view.

    Be aware that any file type can be an attachment, not necessarily HTML...


    - Paul

    Sunday, July 13, 2014 4:04 PM
  • Hi,

    Here is a blog for your reference:

    Display Item Attachments in SharePoint List View

    http://amitphule.blogspot.com/2012/04/display-item-attachments-in-sharepoint.html

    Best Regards


    Dennis Guo
    TechNet Community Support

    Monday, July 14, 2014 3:04 PM
    Moderator
  • Hello Dennis,

    This is exactly what I need but implemented with JSLink. Is there anyway? 

    Actually I want to display the file link.

    Thanks in advance,

    Giorgos

    Wednesday, July 16, 2014 8:00 AM
  • Hi,

    We can use jQuery and JSLink to achieve it.

    The following code for your reference:

    (function () {
    
        // Create object that have the context information about the field that we want to change it output render  
    
        var linkFiledContext = {};
    
        linkFiledContext.Templates = {};
    
        linkFiledContext.Templates.Fields = {
             
            "Attachments": { "View": AttachmentsFiledTemplate }
        };
    
        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(linkFiledContext);
    
    })();
    
    
    // This function provides the rendering logic for list view 
    function AttachmentsFiledTemplate(ctx) {
        var itemId = ctx.CurrentItem.ID;
        var listName = ctx.ListTitle;       
        return getAttachments(listName, itemId);
    }
    
    function getAttachments(listName,itemId) {
      
        var url = _spPageContextInfo.webAbsoluteUrl;
        var requestUri = url + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")/AttachmentFiles";
        var str = "";
        // execute AJAX request
        $.ajax({
            url: requestUri,
            type: "GET",
            headers: { "ACCEPT": "application/json;odata=verbose" },
            async: false,
            success: function (data) {
                for (var i = 0; i < data.d.results.length; i++) {
                    str += "<a href='" + data.d.results[i].ServerRelativeUrl + "'>" + data.d.results[i].FileName + "</a>";
                    if (i != data.d.results.length - 1) {
                        str += "<br/>";
                    }                
                }          
            },
            error: function (err) {
                //alert(err);
            }
        });
        return str;
    }
    

    Save the code above as a js file, then add the js file and jQuery js lib into a document library.

    JSLink refer: ~site/DocumentLib/jquery-1.11.1.min.js|~site/DocumentLib/jslink.js

    Best Regards


    Dennis Guo
    TechNet Community Support

    • Marked as answer by geo82 Thursday, July 17, 2014 9:27 AM
    Thursday, July 17, 2014 1:55 AM
    Moderator
  • Thank you Dennis,

    It works fine.

    Best Regards,

    Giorgos

    Thursday, July 17, 2014 9:27 AM
  • There is no Need for jquery.

    You could do that simply with the SharePoint JS Client-API


    Thursday, July 17, 2014 12:51 PM
  • This works great Dennis. However, I'm noticing it adds about 3 seconds to my list view (onLoad / Paging). I have even moved the logic to OnPostRender but the DOM still locks up. Is there any way to make this async so it doesn't affect performance?
    Friday, October 03, 2014 9:56 PM
  • Hi - this solution works, but gives a warning about async being depricated. I have tried to change it into working asynchronously, but I fail to do so.

    What is the pattern for this? I suspect something about promises and deferreds, but am unable to make it work...

    Any thoughts on this?

    Regards

    Leif

    Thursday, October 13, 2016 7:34 AM
  • I have a Box list view and using jquery-2.2.3.js and it's not working. Any idea why?

    Mike


    SharePoint Engineer - Mike

    Tuesday, May 02, 2017 3:51 PM
  • Its working good.But excel file is getting download. I want to see that file if I click the file url. How can i do it?

    Tuesday, May 23, 2017 9:43 AM