Content Library
When creating custom widgets in Duda, accessing and displaying data dynamically from the Content Library can significantly improve the website building process. By utilizing Handlebars, developers can directly access these properties within the widget's HTML. Additionally, these properties can be accessed within the widget's Javascript through the Content Library API. To fully understand the properties available for use, consult the Content Library Object.
HTML & Handlebars
Access Properties Directly
You can utilize Handlebars to directly access specific properties from your Content Library. This capability allows you to dynamically incorporate various data types, such as images and text into your widgets. Suppose you want to display a business logo stored in the Content Library under business_data
. The property that holds the URL for the logo is logo_url
. Here’s how you can embed this image into your widget using Handlebars:
<img src="{{contentLibrary.business_data.logo_url}}" alt="logo">
Utilize Helpers to Iterate Through Values
Imagine you have a set of custom texts stored in your Content Library under site_texts
, and you want to display specific items based on their labels. For example, you want to find and display the text associated with the label "Our Services".
To begin, access the site_texts
object within the Content Library. The each helper in Handlebars iterates over an array or object. To display the content only if it matches a specific label (in this case, "Our Services"), you'll use a conditional helper. Duda’s Widget Builder supports custom helpers like equals for these comparisons.
<p>
{{#each contentLibrary.site_texts.custom}}
{{#equals label "Our Services"}}
Values: {{text}}
{{/equals}}
{{/each}}
</p>
Error Handling
Always ensure the data you are referencing exists. You can use Handlebar conditionals to check if the property is not empty or undefined before trying to render it.
{{#if contentLibrary.business_data.logo_url}}
<img src="{{contentLibrary.business_data.logo_url}}" alt="logo">
{{else}}
<p>Logo not available.</p>
{{/if}}
Javascript
The Content Library's data can also be accessed within a custom widget's Javascript. Utilize the Content Library API to accomplish this.
const contentLib = await dmAPI.loadContentLibrary();
const customTexts = contentLib.site_texts.custom
for(let i = 0; i< customTexts.length; i++){
if(customTexts[i].label === 'Services'){
console.log('This business has Services offered')
}
}
Updated 6 months ago