winnewoerp
winnewoerp

Reputation: 251

Output items of collection as HTML in Directus

I'm new to Directus. How do I add a loop for all items of a collection here?

// Define a function 'e'
var e = (router) => {

    // Create a GET route for the URL "/"
    router.get("/", (req, res) => {

        // Send a simple HTML response with a header
        let html = "<h1>List of all items</h1>";
        
        // Add loop for items output here
        // ### TBD!
        html += '<ul><li>List of all items of collection \'playgrounds\' to be added here</li></ul>';
        
        res.send(html);
    });
};

// Export the function as the default export
export { e as default };

I found out how to access items generally, but not how to combine this with the above code.

Upvotes: 2

Views: 30

Answers (1)

Gergely Sim&#225;ndi
Gergely Sim&#225;ndi

Reputation: 53

Based on the above code I assume it is an endpoint.

In this case you can access collections using ItemsService.
Here you can find a list of the register function parameters.

Example:

export default (router, { services, getSchema }) => {
    router.get('/', async (req, res) => {
        const { ItemsService } = services;
        
        const playgroundsItemsService = new ItemsService("playgrounds", {
            schema: await getSchema(),
            accountability: req.accountability
        });

        const playgrounds = await playgroundsItemsService.readByQuery({
            fields: ["*"]
        });

        let html = "<h1>List of all items</h1><ul>";
        for (const playground of playgrounds) {
            html += '<li>playground.id</li>';
        }
        html += "</ul>";

        res.send(html);
    });
};

Upvotes: 0

Related Questions