Search code examples
docpadeco

Docpad: get collection item dynamically


I am new to docpad. I have something like filter in my project. There is few switchers to filter a list of icons. After user clicks an icon, the details about chosen item should be shown. This item is in docpad collection. How to implement this? Every icon in the list has the id which is equal to the id of responding item in docpad collection. Is there any way to store id of chosen item in a variable onclick(in order to use it in filter of getCollection or getFileById in eco template)?


Solution

  • I'm unclear about what you want to achieve. If you want to filter items on a page with a user click, something like a masonry/pinterest layout, then the way is to output all collection items to the page and then filter them with client side JavaScript. If you want to display further details when a user clicks on an item, the principle is the same. Output all details of the collection to the page but only make the full details visible when an item is clicked on by the user (again using client side script).

    Now, if the collection is too large or it's contents too long to output to a page and you need to generate content on post back (ie dynamically) then a page can be marked dynamic = true in the metadata. And you will also need to install the clean urls plugin

    Edit:

    As an example of filtering a collection on a dynamically generated page using the eco template system.

    ---
    layout: simple
    dynamic: true
    ---
    
    <%collection = ['Aardvark',"Arrows","Armageddon","Buildings","Bats","Bob the builder"] %>
    <%query = @req.query%>
    <%-query.q%>
    <%filter = query.q%>
    <h1><%-(new Date()).toString()%></h1>
    <ul>
    <% for item in collection:%>
    <%if item[0].toLowerCase() == filter or !filter:%>
        <li><%-item%></li>
    <%end%>
    <%end%>
    </ul>
    

    This assumes that there is a query parameter in the form of q=aor q=betc. ie http://127.0.0.1:9778/?q=a. I've also written out the date to prove that the page is regenerated on each request.

    Checkout the metadata section of the DocPad documentation.