### Run Local Static Server with serve CLI Source: https://docs.webstudio.is/university/self-hosting This command starts a simple local server to host your static Webstudio project files. It's necessary because the static files rely on absolute URLs. Make sure you have Node.js and npm installed, then run this command in your project's root directory. ```shell npx serve . ``` -------------------------------- ### Install and Verify Webstudio CLI Source: https://docs.webstudio.is/university/self-hosting/cli Installs the Webstudio CLI globally using npm and verifies the installation by checking the CLI version. It also explains how to update the CLI. ```bash npm install -g webstudio ``` ```bash webstudio --version ``` -------------------------------- ### Install Node.js using NVM Source: https://docs.webstudio.is/university/self-hosting/cli Installs Node.js version 20 or greater using the Node Version Manager (NVM). This is a prerequisite for using the Webstudio CLI. ```bash curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash ``` ```bash nvm install 20 ``` ```bash node --version ``` -------------------------------- ### Resource Fetching Example in Webstudio Source: https://docs.webstudio.is/university/foundations/cms Illustrates how to use a Resource variable in Webstudio to fetch data from a CMS based on URL parameters. The example shows a query that dynamically retrieves posts matching a 'slug' parameter from the URL. ```text `posts(slug: system.params.slug)` ``` -------------------------------- ### Atomic CSS Example (Enabled) Source: https://docs.webstudio.is/university/foundations/project-settings Demonstrates the CSS output generated by Webstudio when Atomic CSS is enabled. Each style is associated with a unique, optimized class for efficient CSS file size. ```css .ceszdr { background-color: #fff; } .c1jykks9 { border-top-left-radius: 1rem; } .c31r7mo { border-top-right-radius: 1rem; } .cywm6f1 { border-bottom-left-radius: 1rem; } .c1q77ydo { border-bottom-right-radius: 1rem; } .cu6yur2 { padding: 20px; } ``` -------------------------------- ### Token Naming Convention for Style Guide Source: https://docs.webstudio.is/university/craft This convention specifies how to prefix tokens used solely for dressing up the style guide. It ensures these tokens are distinct from those intended for actual site usage. The prefix is a double underscore, and the casing convention is kebab-case. ```CSS /* Convention for style guide tokens */ /* Prefix with double underscore */ /* Kebab casing */ .icon { /* Example Token */ --__icon-size-small: 16px; --__icon-color-primary: #333; } ``` -------------------------------- ### Run Development Server in Webstudio Source: https://docs.webstudio.is/contributing/contributing-for-developers This command starts the development server for the Webstudio project. It's typically run after the project has been set up in a VS Code Dev Container. The output will provide a local URL to access the application. ```sh pnpm dev ``` -------------------------------- ### Create Notion Resource Variable Source: https://docs.webstudio.is/university/integrations/notion This snippet demonstrates how to set up a 'Resource' variable in Webstudio, which is essential for fetching data from external sources like Notion. It includes an example of how to dynamically filter data based on a URL slug. ```json { "filter": { "property": "Slug", "rich_text": { "equals": system.params.slug } } } ``` -------------------------------- ### CSS Example (Atomic CSS Disabled) Source: https://docs.webstudio.is/university/foundations/project-settings Illustrates the CSS output when Atomic CSS is disabled. Classes are more human-readable, combining default component classes with token and style information, which can be useful for manual CSS modifications. ```css .w-box-1 { background-color: rgb(255, 255, 255); border-radius: 1rem; padding: 20px; } ``` -------------------------------- ### Deploy JavaScript Application with Vercel CLI Source: https://docs.webstudio.is/university/self-hosting/vercel This command deploys a locally built Webstudio project as a JavaScript application to Vercel. It requires the Vercel CLI to be installed and assumes the project has already been built using the Webstudio CLI. ```shell vercel deploy ``` -------------------------------- ### CSS Variable Examples for Animation Sequencing Source: https://docs.webstudio.is/university/core-components/animation-group Demonstrates using special CSS variables '--index' and '--total' to create dynamic animations for child elements within an Animation Group. These examples show how to apply unique rotations, translations, and distributions based on the element's position and the total count of elements. ```css /* Creating unique rotations for each child element */ .child-element { transform: rotate(calc(var(--index) * 45deg)); } /* Applying varying translations */ .child-element { transform: translateX(calc(var(--index) * 100px)); } /* Adjusting animations relative to the total number of elements */ .child-element { width: calc(100% / var(--total)); } ``` -------------------------------- ### Webstudio: Binding data with string concatenation Source: https://docs.webstudio.is/university/integrations/airtable This example demonstrates how to dynamically construct a URL for linking to individual Airtable records within a Webstudio Collection. It concatenates a static base path with a dynamic slug. ```webstudio "products/" + CollectionItem.slug ``` -------------------------------- ### Data Binding Example in Webstudio Source: https://docs.webstudio.is/university/foundations/cms Shows how to bind CMS data to Webstudio components using the Expression Editor. This example demonstrates accessing a 'title' field from a 'CMS Data' Resource Variable and binding it to a component's text content. ```text `CMS Data.title` ``` -------------------------------- ### Paste CSS Declarations into Webstudio Style Panel Source: https://docs.webstudio.is/university/foundations/copy-paste/css This demonstrates the basic process of copying CSS declarations and pasting them into the Advanced section of Webstudio's Style Panel. Webstudio parses these declarations to populate the corresponding style fields. ```css background: blue; ``` -------------------------------- ### JavaScript Array Example for Collections Source: https://docs.webstudio.is/university/core-components/collection Illustrates the structure of a JavaScript array used for populating a Webstudio Collection. Each object in the array represents an item to be displayed, containing properties like 'title'. This format is crucial for correct data binding. ```javascript 0 { title: "Hello world"}, 1 { title: "Lorem ipsum"}, 2 { title: "Webstudio rocks!" } ``` -------------------------------- ### Using a CSS Variable Source: https://docs.webstudio.is/university/foundations/css-variables Demonstrates how to use a defined CSS variable within Webstudio. The example shows the common syntax `var(--my-var)` which Webstudio's autocomplete can also assist with. ```css var(--my-var) ``` -------------------------------- ### Link to Individual Notion Records in Collection Source: https://docs.webstudio.is/university/integrations/notion This example demonstrates how to construct a link to a specific Notion record's dynamic page within a Webstudio Collection component. It concatenates a static base path with a dynamic slug value obtained from the Notion data. ```javascript "/events/" + ``` -------------------------------- ### Initiate and Link Webstudio Project Source: https://docs.webstudio.is/university/self-hosting/cli Initiates a Webstudio project on your local machine by connecting to Webstudio Cloud and provides the command to link a project from Webstudio Cloud. ```bash webstudio ``` ```bash webstudio link ``` -------------------------------- ### Build Webstudio Project for Netlify Serverless Functions Source: https://docs.webstudio.is/university/self-hosting/netlify Builds a Webstudio project specifically for Netlify, configuring it to use serverless functions. This command prepares the project for a serverless deployment target. ```bash webstudio build --template netlify ``` -------------------------------- ### Build Webstudio Project Source: https://docs.webstudio.is/university/self-hosting/cli Builds the Webstudio project. It can build a dynamic JavaScript application or a static site using the `--template ssg` option. ```bash webstudio build ``` ```bash webstudio build --template ssg ``` -------------------------------- ### Deploy JavaScript App with Netlify CLI Source: https://docs.webstudio.is/university/self-hosting/netlify Deploys a dynamic JavaScript application to Netlify using the Netlify command-line interface. This command initiates the deployment process. ```bash netlify deploy ``` -------------------------------- ### Develop JavaScript Application Source: https://docs.webstudio.is/university/self-hosting/cli Steps to run the built JavaScript application in development mode or build a production version. Assumes the project is scaffolded using the default Remix template. ```bash npm install ``` ```bash npm run dev ``` ```bash npm run build ``` -------------------------------- ### Webstudio CLI Commands for Docker Build Source: https://docs.webstudio.is/university/self-hosting/flightcontrol Commands to sync Webstudio project data and build it specifically for Docker deployment. Ensure you publish in the builder before syncing to generate the latest build data. ```bash webstudio sync webstudio build --template docker ``` -------------------------------- ### Configure GraphQL Resource for WordPress Source: https://docs.webstudio.is/university/integrations/wordpress Steps to set up a GraphQL Resource in Webstudio to fetch data from WordPress, including defining the URL, constructing a query, and setting variables. ```APIDOC ## POST /graphql ### Description Configures a GraphQL Resource in Webstudio to fetch data from a headless WordPress site. ### Method POST ### Endpoint /graphql #### Query Parameters None #### Request Body **url** (string) - Required - The URL of the WordPress website appended with `/graphql`. **query** (string) - Required - The GraphQL query constructed using Query Composer. **variables** (object) - Required - An object containing variables for the GraphQL query, typically mapping dynamic URL parameters to query fields. ### Request Example ```json { "url": "https://wordpress.example.com/graphql", "query": "query GetPost($slug: String!) { post(id: $slug, idType: SLUG) { title content featuredImage { altText sourceUrl width height } } }", "variables": { "id": "system.params.slug" } } ``` ### Response #### Success Response (200) - **data** (object) - Contains the data fetched from WordPress. #### Response Example ```json { "data": { "post": { "title": "Example Post Title", "content": "

This is the rendered content of the post.

", "featuredImage": { "altText": "Featured image alt text", "sourceUrl": "https://wordpress.example.com/wp-content/uploads/image.jpg", "width": 800, "height": 600 } } } } ``` #### Error Handling - **400 Bad Request**: If the URL, query, or variables are malformed. - **404 Not Found**: If the GraphQL endpoint or specified post slug is not found. - **500 Internal Server Error**: If there's an issue on the WordPress server. ``` -------------------------------- ### Sync Webstudio Project with Cloud Source: https://docs.webstudio.is/university/self-hosting/cli Synchronizes your local Webstudio project with the project in Webstudio Cloud. This command should be run after publishing changes in the Cloud. ```bash webstudio sync ``` -------------------------------- ### Fetch Blog Posts using GraphQL Source: https://docs.webstudio.is/university/integrations/flotiq A GraphQL query to fetch a list of blog posts, including their ID, title, slug, excerpt, and header image details. This query is used to populate listing pages. ```graphql query Posts { blogpostList { id title slug excerpt headerImage { alt url } } } ``` -------------------------------- ### Navigator Item Naming Conventions Source: https://docs.webstudio.is/university/craft Guidelines for naming various items within the Web Studio navigator, including labels, generic components like Box and Slot, and hierarchical parent-child relationships. The aim is to provide semantic and human-readable names. ```HTML ``` -------------------------------- ### Webstudio Dynamic Page Path Configuration Source: https://docs.webstudio.is/university/integrations/notion Configures a dynamic page in Webstudio to display individual records from a Notion database. The path uses a dynamic segment like ':slug' to fetch specific records based on the URL. ```Webstudio Pages > Create a new page. Add a path with at least two segments in the Dynamic Path field. This example uses the path `/events/:slug`. ``` -------------------------------- ### GraphQL Resource Fetching in Webstudio Source: https://docs.webstudio.is/university/foundations/cms Provides information on using GraphQL resources within Webstudio for data fetching. This is relevant when interacting with APIs that support GraphQL queries. ```text See the [GraphQL resource](https://docs.webstudio.is/university/variables#graphql) documentation. ``` -------------------------------- ### Configure GitHub OAuth App Source: https://docs.webstudio.is/contributing/contributing-for-developers Details on creating a GitHub OAuth application for Webstudio. Requires setting specific URLs for the homepage and callback. The application must be accessed via the specified homepage URL for GitHub login to function correctly. ```plaintext Name: Webstudio Homepage URL: http://localhost:3000 Authorization callback URL: http://localhost:3000/auth/github/callback ``` -------------------------------- ### Convert Hygraph Query for Pagination Source: https://docs.webstudio.is/university/integrations/hygraph Modifies an existing Hygraph GraphQL query to support pagination using the `postsConnection` field, `first`, and `skip` arguments. This enables fetching data in chunks and managing navigation between pages. ```graphql query Posts($first: Int, $skip: Int = 0) { postsConnection( first: $first skip: $skip orderBy: publishedAt_DESC ) { pageInfo { hasNextPage hasPreviousPage } edges { node { title slug ... } } } } ``` -------------------------------- ### Enable Dev Login in Webstudio Source: https://docs.webstudio.is/contributing/contributing-for-developers Configuration for enabling a development-only login flow in the Webstudio builder. This involves creating a `.env.development` file in the `apps/builder` directory and setting specific environment variables. It allows developers to log in without needing an external authentication provider. ```dotenv DEV_LOGIN=true AUTH_SECRET=a random value ``` -------------------------------- ### Dynamically Fetching Blogs with Search Query Source: https://docs.webstudio.is/university/core-components/form This JavaScript expression demonstrates how to dynamically construct an API URL to fetch blog posts, including a search parameter if provided by the user. It utilizes the System Variable `system.search.searchBlog` to access the search term entered in a form input named 'searchBlog'. The expression uses a ternary operator and template literals to conditionally append the query parameter. ```javascript `/api/blogs${system.search.searchBlog ? `?search=${system.search.searchBlog}` : ''}` ``` -------------------------------- ### GraphQL Query for Blogpost Data Source: https://docs.webstudio.is/university/integrations/flotiq This GraphQL query fetches a single blog post from Flotiq based on its slug. It retrieves the post's ID, title, slug, excerpt, and header image URL and alt text. This is used within Webstudio's GraphQL Data Variable. ```graphql query Post($slug: String = "") { blogpost(field: "slug", value: $slug) { id title slug excerpt headerImage { alt url } } } ``` -------------------------------- ### Create Dynamic Link in Webstudio Source: https://docs.webstudio.is/university/integrations/wordpress This snippet demonstrates how to create a dynamic link in Webstudio by concatenating a static base path with a dynamic slug value from a data source. It's used for navigation to specific content items. ```webstudio "/blogs/" + WordPress Post.slug ``` -------------------------------- ### Simple Animations with Direct Style Source: https://docs.webstudio.is/university/core-components/animation-group Demonstrates how to animate common properties like opacity, rotation, and translation using the direct style animation pattern. The Animation Group directly controls the styles of its child elements. ```css /* Fade in example */ .element { opacity: 0; } ``` ```css /* Rotate example */ .element { rotate: 50deg; } ``` ```css /* Translate Y example */ .element { translate: 0 200px; } ``` ```css /* Grow box shadow example */ .element { box-shadow: 0 0 50px 100px black; } ``` ```css /* Shrink box shadow example (for comparison) */ .element { box-shadow: 0 0 25px 50px black; } ``` -------------------------------- ### Embed GSAP library and create animation with JavaScript Source: https://docs.webstudio.is/university/how-tos/how-to-add-a-gsap-animation This snippet demonstrates how to include the GSAP animation library and its Flip plugin using CDN links within an HTML embed component. It then shows a basic `gsap.fromTo` animation targeting elements with the class 'animation', setting opacity and duration. ```html ``` -------------------------------- ### Dynamic Page URL Parameters in Webstudio Source: https://docs.webstudio.is/university/foundations/cms Demonstrates how to define dynamic parameters in page paths for Webstudio. Parameters like ':name', ':name?', '/*', and '/:name*' allow for flexible URL structures that enable dynamic content display based on URL segments. ```text `/post/:slug` `/user/:name?` `/*` `/:name*` ``` -------------------------------- ### Convert GraphQL Posts Query for Cursor Pagination Source: https://docs.webstudio.is/university/integrations/wordpress Modifies an existing GraphQL query to support cursor-based pagination. It changes the structure from `posts.nodes` to `posts.edges.node` and includes `pageInfo` for navigation. This is essential for fetching content in batches. ```graphql query Posts { ... posts { nodes { title(format: RENDERED) slug ... } } } ``` ```graphql query Posts($search: String = "", $first: Int, $after: String) { posts(where: {search: $search}, first: $first, after: $after) { pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { cursor, node { title(format: RENDERED) slug ... } } } } ``` -------------------------------- ### Basic HTML Embed with YouTube Video Source: https://docs.webstudio.is/university/core-components/html-embed Demonstrates how to embed a YouTube video using the HTML Embed component. This is a common use case for integrating external media content into a Webstudio project. ```html {% embed url="" %} ``` -------------------------------- ### Set GitHub Environment Variables Source: https://docs.webstudio.is/contributing/contributing-for-developers Instructions for adding GitHub client ID and client secret to the project's environment variables. These are necessary for the application to authenticate with GitHub. ```plaintext GH_CLIENT_SECRET= GH_CLIENT_ID= ``` -------------------------------- ### GraphQL Resource Variables Configuration Source: https://docs.webstudio.is/university/foundations/variables Configuration options for a GraphQL Resource variable in Webstudio. This includes specifying the GraphQL API endpoint, the query to execute, and any variables to pass into the query. The 'Variables' field accepts a JavaScript object, commonly used with dynamic pages to pass parameters. ```javascript { "URL": "your-graphql-api-endpoint", "Query": "query GetPost($slug: String!) { post(slug: $slug) { title, content } }", "Variables": "{ \"slug\": system.params.slug }" } ``` -------------------------------- ### Bind Image Source in Webstudio Source: https://docs.webstudio.is/university/integrations/flotiq Demonstrates how to bind an image component's source property to a URL retrieved from Flotiq data. It shows string concatenation for constructing the image URL. ```javascript "https://api.flotiq.com/" + VariableName.data.data.blogpost.headerImage[0].url ``` -------------------------------- ### Correct DNS Records for .co.uk Domains Source: https://docs.webstudio.is/university/foundations/publishing-and-custom-domains Provides the correct DNS record values for domains with country codes like '.co.uk', as the default records provided by Webstudio may be incorrect for these specific TLDs. This ensures proper domain configuration. ```DNS CNAME record: @ (instead of example) ``` ```DNS TXT record: _webstudio_is (instead of _webstudio_is.example) ``` -------------------------------- ### Constructing Dynamic Airtable API URL with Webstudio Expression Editor Source: https://docs.webstudio.is/university/integrations/airtable This snippet demonstrates how to build a dynamic URL for fetching Airtable data using Webstudio's Expression Editor. It filters records based on a URL parameter, requiring a column name from Airtable and a dynamic path segment from the system. ```javascript `https://example.com?filterByFormula={YOUR_COLUMN_NAME}="${system.params.YOUR_DYNAMIC_PATH}"` ``` -------------------------------- ### Craft CSS Variables Source: https://docs.webstudio.is/university/craft This snippet lists the custom CSS variables provided by Craft, which are based on Open Props and extended with specific design tokens for foreground, background, spacing, focus, and duration. These variables facilitate adaptive and consistent design, and their values can be customized to match branding. ```css --foreground-primary --foreground-secondary --foreground-accent --foreground-muted --foreground-border --background-primary --background-secondary --background-accent --background-card --gap-xs --gap-s --gap-m --gap-l --focus-color --focus-width --focus-offset --duration-default --easing-default ``` -------------------------------- ### GraphQL Variables for Dynamic Slug Binding Source: https://docs.webstudio.is/university/integrations/flotiq This JSON object defines the variables for a GraphQL query in Webstudio. It dynamically binds the 'slug' variable to the 'slug' parameter extracted from the current page's URL, allowing content fetching based on the specific blog post being viewed. ```json { "slug": "system.params.slug" } ``` -------------------------------- ### Configure Webhook Trigger in N8N Source: https://docs.webstudio.is/university/integrations/n8n Sets up a webhook trigger in n8n to receive data from Webstudio Forms. Requires HTTP POST method and a unique webhook URL. ```javascript Add a Webhook node to your workflow by going to Add first step > Select a trigger > On webhook call Set HTTP Method to POST. Copy the “Test Webhook URL” and head over to Webstudio. ``` -------------------------------- ### Bind Collection Data in Webstudio Source: https://docs.webstudio.is/university/integrations/flotiq Shows how to bind a list of data items (array) from a Data Variable to a collection component in Webstudio. It specifies the path to access the list data. ```javascript .data.data.List ``` -------------------------------- ### Update Container Token to Flexbox (CSS) Source: https://docs.webstudio.is/university/craft This snippet demonstrates how to update the 'container' token to use flexbox for improved compatibility with the Craft Library. It involves setting display to flex, flex-direction to column, and gap to a CSS variable. Manual adjustments are needed for horizontal layouts. ```css /* Update container token for Craft Library compatibility */ .container { display: flex; flex-direction: column; gap: var(--gap-m); } ``` -------------------------------- ### Connect Webstudio Form to N8N Webhook Source: https://docs.webstudio.is/university/integrations/n8n Configures a Webstudio Form to send data to an n8n webhook. Involves setting 'Action' and 'Method' properties in the form's settings and naming input fields. ```javascript Open the Webstudio builder, select your form instance, go to Settings and add two properties— Action and Method. Paste your copied Test Webhook into the Action property. Write the word “POST" in the Method property. Name every input field in your form so n8n can identify them in a form submission. ``` -------------------------------- ### HTML Structure for Text Animation Source: https://docs.webstudio.is/university/core-components/text-animation This HTML structure demonstrates how the Text Animation component automatically wraps text elements for animation. The parent Animation Group can then target each span individually. The space between words is handled by a commented-out span. ```html

Hello World

``` -------------------------------- ### Defining a CSS Variable Source: https://docs.webstudio.is/university/foundations/css-variables Shows the syntax for defining a CSS variable by prefixing the variable name with two dashes. This variable can then hold values like colors, gradients, durations, or numbers. ```css --gray-5 ``` -------------------------------- ### Set Status Code for Notion Data Binding Source: https://docs.webstudio.is/university/integrations/notion This JavaScript expression is used in Webstudio's Page Settings to determine the HTTP status code based on the existence of a Notion slug value. If the value exists, it returns 200 (OK); otherwise, it returns 404 (Not Found). ```javascript ? 200 : 404 ``` -------------------------------- ### Integrate Supabase with N8N Workflow Source: https://docs.webstudio.is/university/integrations/n8n Adds a Supabase node to an n8n workflow to create a new row with submitted form data. Requires linking a Supabase account and mapping form fields to Supabase table columns. ```javascript Go to Add Node > Action in an app > Supabase > Create a row Select the Supabase account you have linked to n8n and modify the other relevant parameters. Link your form’s input fields to your Supabase table by mapping them to your Webhook’s Output Data. ``` -------------------------------- ### Add A Record for Proxied Traffic Source: https://docs.webstudio.is/university/foundations/publishing-and-custom-domains Configure an A record to point to a specific IP address. This allows Cloudflare to apply rules, redirects, and Workers to incoming traffic, even if the domain is not directly routed to an origin server. The equivalent AAAA record IP is 100::. ```DNS A record: 192.0.2.1 ``` ```DNS AAAA record: 100:: ``` -------------------------------- ### Custom Property Animation with CSS Variables Source: https://docs.webstudio.is/university/core-components/animation-group Illustrates animating custom properties (CSS variables) for more maintainable and reusable animations. The Animation Group controls the values of these variables, which are then applied in the Style Panel. ```css /* Define custom property in Style Panel */ .element { --child-rotate: 50deg; rotate: var(--child-rotate); } ``` ```css /* Animate custom property value in Animation Group */ .animated-group { --child-rotate: 100deg; } ``` -------------------------------- ### Implement Conditional Logic with IF Node in N8N Source: https://docs.webstudio.is/university/integrations/n8n Uses an IF node in n8n to evaluate conditions for triggering subsequent actions, such as sending Slack notifications. Demonstrates setting a condition based on a form field value. ```javascript Go to Add Node > Flow > IF. Add a condition that sets your IF node to “true” if the value from your input is $10,000 or under. Click on “Execute Node” This will return a true/false result. a. On “true”, the value is under $10,000. b. On “false”, the value is over $10,000. ``` -------------------------------- ### Set WordPress Post ID via URL Parameter Source: https://docs.webstudio.is/university/integrations/wordpress This JavaScript snippet configures the 'id' variable for a GraphQL query in Webstudio. It dynamically sets the ID to the 'slug' parameter from the current URL, allowing the query to fetch specific WordPress posts based on their URL slugs. ```javascript { id: system.params.slug } ``` -------------------------------- ### Dynamic Status Code Expression in JavaScript Source: https://docs.webstudio.is/university/integrations/wordpress This JavaScript expression dynamically sets the HTTP status code for a page. It checks if a specific WordPress field (e.g., title) has a value. If a value exists, it returns a 200 status code (OK); otherwise, it returns a 404 status code (Not Found). This is useful for SEO and user experience when content might be missing. ```javascript return ? 200 : 404; ``` -------------------------------- ### Payload CMS: Convert Rich Text to HTML Source: https://docs.webstudio.is/university/foundations/cms This snippet demonstrates how to automatically convert rich text content from one field into HTML and save it in another field within Payload CMS. It requires creating a custom field and a hook to achieve this functionality. ```javascript /** * Example demonstrating how to convert rich text to HTML in Payload CMS. * This involves defining a field for rich text and another for HTML output, * and using a hook to perform the conversion. */ // Assume 'richTextField' is your Rich Text field configuration // Assume 'htmlOutputField' is your HTML output field configuration // Example hook structure (actual implementation may vary based on Payload version and schema) const yourHook = { beforeChange: [async ({ req, data, operation }) => { if (operation === 'create' || operation === 'update') { const richTextContent = data.richTextField; if (richTextContent) { // Logic to convert richTextContent to HTML // This would typically involve using a library like Lexical's HTML converter const htmlContent = convertRichTextToHtml(richTextContent); data.htmlOutputField = htmlContent; } } return data; }], }; // Placeholder for the conversion function function convertRichTextToHtml(richText) { // Replace with actual Lexical or other rich text to HTML conversion logic console.log('Converting rich text to HTML:', richText); return `

${JSON.stringify(richText)}

`; // Dummy HTML output } // In your collection config, you would add this hook: // collections: [ // { // ... // hooks: yourHook, // ... // } // ] ``` -------------------------------- ### JavaScript - Schema Binding with Template Literals Source: https://docs.webstudio.is/university/foundations/expression-editor This snippet demonstrates how to bind CMS data to a JSON-LD schema within an HTML embed component. It uses template literals to dynamically insert data like titles, image URLs, and dates into the schema. Ensure to replace placeholders like YOUR.CMS.TITLE with actual CMS variable paths. ```javascript ``` -------------------------------- ### Set 404 Status Code Based on CMS Data (JavaScript) Source: https://docs.webstudio.is/university/foundations/expression-editor This JavaScript expression binds to the Page Settings > Status Code to dynamically determine if a page should return a 404 (not found) or 200 (success) status. It checks for the existence of a specific data key (e.g., 'id') in the CMS response. If the key is present, it returns 200; otherwise, it returns 404. Replace 'cmsData.data[0].id' with a key that reliably indicates data presence in your CMS. ```javascript cmsData.data[0].id ? 200 : 404 ``` -------------------------------- ### Set Status Code with Airtable Data in JavaScript Source: https://docs.webstudio.is/university/integrations/airtable This snippet demonstrates how to conditionally set the HTTP status code for a page based on the presence of data from an Airtable source. It uses a ternary operator to return 200 if the Airtable value exists, and 404 otherwise. This is useful for SEO and user experience when content is not available. ```javascript ? 200 : 404 ``` -------------------------------- ### Avoiding Global Variables in HTML Embed Scripts Source: https://docs.webstudio.is/university/core-components/html-embed Illustrates the problem of creating global variables within script tags in HTML embeds and provides solutions using module scope or Immediately Invoked Function Expressions (IIFE) to maintain local scope. ```html ``` ```html ``` ```html ``` -------------------------------- ### Conditionally Hide Collection Item (JavaScript) Source: https://docs.webstudio.is/university/foundations/expression-editor This JavaScript expression is used to conditionally hide collection items. It compares the current page's slug with the collection item's slug and returns false (hides the item) if they match, preventing the current post from appearing in related posts. Customize 'slug' and 'collectionItem.slug' to match your project's variables. ```javascript system.params.slug === collectionItem.slug ? false : true ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.