How can I grab a Webflow collection based on its ID and store it in a variable? Can someone provide a snippet or example image? Also, is there a way to link embedHTML on the same page to share or access variables from each other (top-bottom)?

TL;DR
  • Access Webflow's CMS API by obtaining your API Key through the Project Settings under the Integrations tab.
  • Use JavaScript in Webflow Designer to fetch collection data via the API, ensuring your API key is secure.
  • Define global JavaScript variables to share data between different script sections within Webflow.

To grab a Webflow collection based on its ID and store it in a variable, you need to utilize JavaScript within the Webflow Designer custom code section. This involves using an API to fetch collection data.

1. Access Webflow's CMS API

  • Sign in to your Webflow account and go to Project Settings.
  • Navigate to the Integrations tab, and scroll down to the API section to find your API Key.
  • Note: Ensure the site plan includes CMS hosting to access API features.

2. Fetch Collection Data

  • Use JavaScript to fetch data from the collection via the API.
  • Example inline code (adjust the placeholders with actual data):

  ```javascript

  const collectionId = 'your-collection-id';

  const apiKey = 'your-api-key';

  const url = https://api.webflow.com/collections/${collectionId}/items;

  fetch(url, {

    method: 'GET',

    headers: {

      'Authorization': Bearer ${apiKey},

      'accept-version': '1.0.0'

    }

  })

  .then(response => response.json())

  .then(data => {

    let items = data.items; // replace 'items' with desired variable name

    console.log(items);

  })

  .catch(error => console.error('Error fetching collection data:', error));

  ```

  • Ensure to keep your API key secure and not exposed on the client-side code.

3. Sharing Variables Between Embedded HTML

  • JavaScript can be used to share data between different <script> sections in Webflow.
  • Define a global JavaScript variable atop your script within Webflow’s custom code editor.
  • Reference this variable in subsequent script tags or embeds.
  • The initial script:

  ```javascript

  window.myWebflowVariable = {};

  ```

  • Use this in another section:

  ```javascript

  window.myWebflowVariable['anotherKey'] = 'anotherValue';

  console.log(window.myWebflowVariable);

  ```

Summary

To fetch and store a Webflow collection based on its ID, utilize Webflow's CMS API through JavaScript. Use global variables to enable data sharing between separate script sections on the same page. Always protect your API key to prevent unauthorized access.

Rate this answer

Other Webflow Questions