### Install Scrivito JS SDK Source: https://github.com/scrivito/scrivito_sdk_js/blob/main/README.md Use this command to install the Scrivito JS SDK into an existing web project. Ensure you have signed up at my.scrivito.com first. ```bash npm install scrivito ``` -------------------------------- ### Configure Scrivito SDK Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Initializes the Scrivito SDK with instance credentials and configuration options. Essential for multi-site setups, custom routing, and visitor authentication. ```javascript import * as Scrivito from 'scrivito'; // Basic configuration Scrivito.configure({ instanceId: 'your-scrivito-instance-id', adoptUi: true, // Enable the editing UI }); ``` ```javascript import * as Scrivito from 'scrivito'; // Advanced multi-site configuration Scrivito.configure({ instanceId: 'your-scrivito-instance-id', adoptUi: true, strictSearchOperators: true, contentTagsForEmptyAttributes: false, // Multi-site routing baseUrlForSite: (siteId) => { if (siteId === 'main') return 'https://www.example.com'; if (siteId === 'blog') return 'https://blog.example.com'; return `https://${siteId}.example.com`; }, siteForUrl: (url) => { const hostname = new URL(url).hostname; if (hostname === 'www.example.com') return { siteId: 'main' }; if (hostname === 'blog.example.com') return { siteId: 'blog' }; return { siteId: hostname.split('.')[0] }; }, // Custom homepage homepage: () => Scrivito.Obj.getByPath('/'), // Visitor authentication visitorAuthentication: true, // Data integration for external data sources activateDataIntegration: true, // Responsive image breakpoints responsiveBreakpoints: { small: 576, medium: 768, large: 992, xlarge: 1200, }, }); ``` -------------------------------- ### Scrivito.provideComponent Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Registers a React component to render a specific Obj or Widget class. The component receives the page/widget instance as a prop and can access its attributes using the `get()` method. ```APIDOC ## Scrivito.provideComponent ### Description Registers a React component to render a specific Obj or Widget class. The component receives the page/widget instance as a prop and can access its attributes using the `get()` method. ### Usage ```javascript import * as Scrivito from 'scrivito'; Scrivito.provideComponent('ClassName', ({ obj }) => ( // React component JSX )); ``` ### Component Examples #### Page Component ```javascript import * as Scrivito from 'scrivito'; Scrivito.provideComponent('Page', ({ page }) => (

{page.get('title')}

)); ``` #### Image Widget Component ```javascript import * as Scrivito from 'scrivito'; Scrivito.provideComponent( 'ImageWidget', ({ widget }) => { const image = widget.get('image'); const link = widget.get('link'); const imageElement = (
{widget.get('caption') && (
{widget.get('caption')}
)}
); if (link) { return {imageElement}; } return imageElement; }, { loading: ({ widget }) => (
Loading image...
), } ); ``` #### Column Widget Component ```javascript import * as Scrivito from 'scrivito'; Scrivito.provideComponent('ColumnWidget', ({ widget }) => (
)); ``` ``` -------------------------------- ### Scrivito.configure Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Initializes the Scrivito SDK with instance credentials and configuration options such as multi-site routing, visitor authentication, and responsive breakpoints. ```APIDOC ## Scrivito.configure ### Description Initializes the Scrivito SDK with your CMS instance credentials and configuration options. This must be called before using any other Scrivito functionality. ### Parameters #### Request Body - **instanceId** (string) - Required - The unique identifier for your Scrivito CMS instance. - **adoptUi** (boolean) - Optional - Enables the integrated in-place editing UI. - **visitorAuthentication** (boolean) - Optional - Enables visitor authentication features. - **activateDataIntegration** (boolean) - Optional - Enables data integration with external sources. - **responsiveBreakpoints** (object) - Optional - Defines pixel widths for responsive image handling. ### Request Example { "instanceId": "your-scrivito-instance-id", "adoptUi": true, "visitorAuthentication": true } ``` -------------------------------- ### Create and Manipulate Widgets Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Demonstrates how to instantiate, update, copy, and delete widgets, as well as how to manage widget lists within page objects. ```javascript import * as Scrivito from 'scrivito'; // Create a new widget const textWidget = new Scrivito.Widget({ _objClass: 'TextWidget', text: '

Hello, world!

', alignment: 'center', }); // Create a widget and add to a page const page = Scrivito.Obj.get('page-id'); const newWidget = new Scrivito.Widget({ _objClass: 'ImageWidget', image: Scrivito.Obj.get('image-id'), caption: 'A beautiful image', displayWidth: 'full', }); // Add widget to widgetlist (in editing context) const currentWidgets = page.get('body') || []; page.update({ body: [...currentWidgets, newWidget], }); // Update widget attributes const widget = page.widget('widget-id'); widget.update({ text: '

Updated text content

', }); // Copy a widget const copiedWidget = widget.copy(); // Delete a widget widget.delete(); // Access widget's parent Obj const parentObj = widget.obj(); // Access widget's container (Obj or another Widget) const container = widget.container(); // Get all widgets on a page const allWidgets = page.widgets(); ``` -------------------------------- ### Handle Links and Binaries Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Covers creating internal and external links, accessing link properties, and rendering links within React components. ```javascript import * as Scrivito from 'scrivito'; // Internal link to an Obj const page = Scrivito.Obj.getByPath('/about'); const internalLink = new Scrivito.Link({ obj: page, title: 'About Us', }); // External link const externalLink = new Scrivito.Link({ url: 'https://www.example.com', title: 'Visit Example', target: '_blank', rel: 'noopener noreferrer', }); // Link with query and hash const linkWithParams = new Scrivito.Link({ obj: page, query: 'tab=contact', hash: 'form', title: 'Contact Form', }); // Access link properties console.log(internalLink.title()); // "About Us" console.log(internalLink.obj()); // Obj instance console.log(internalLink.isInternal()); // true console.log(externalLink.url()); // "https://www.example.com" console.log(externalLink.target()); // "_blank" console.log(externalLink.isExternal()); // true // Copy link with modifications const modifiedLink = internalLink.copy({ title: 'Learn More About Us', hash: 'team', }); // Use link in component function CallToAction({ link }) { if (!link) return null; return ( {link.title() || 'Click Here'} ); } ``` -------------------------------- ### Scrivito.navigateTo Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Programmatically navigate to a page, link, or URL, supporting SPA routing and external destinations. ```APIDOC ## Scrivito.navigateTo ### Description Programmatically navigate to a page, link, or URL. Works with SPA routing and handles both internal and external destinations. ### Parameters - **destination** (Obj/Link/String/Function) - Required - The target to navigate to. - **options** (Object) - Optional - Navigation options including { params: Object, hash: String }. ``` -------------------------------- ### Navigate programmatically with Scrivito.navigateTo Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Handles navigation to internal objects, links, or external URLs. Supports query parameters, hash fragments, and lazy evaluation via functions. ```javascript import * as Scrivito from 'scrivito'; // Navigate to an Obj const page = Scrivito.Obj.getByPath('/about'); Scrivito.navigateTo(page); // Navigate to a Link const link = page.get('ctaLink'); Scrivito.navigateTo(link); // Navigate with query parameters Scrivito.navigateTo(page, { params: { tab: 'details', ref: 'header' } }); // Navigate with hash Scrivito.navigateTo(page, { hash: 'section-features' }); // Navigate with both params and hash Scrivito.navigateTo(page, { params: { filter: 'active' }, hash: 'results', }); // External URL Scrivito.navigateTo('https://www.example.com/external-page'); // Navigate with function (lazy evaluation) Scrivito.navigateTo(() => Scrivito.Obj.getByPermalink('contact')); // In event handlers function handleSubmit(formData) { submitForm(formData).then(() => { Scrivito.navigateTo(thankYouPage); }); } ``` -------------------------------- ### Scrivito.provideEditingConfig Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Configures the editing UI for a content class, including attribute labels, descriptions, property groups, validation, and custom editors. ```APIDOC ## Scrivito.provideEditingConfig ### Description Configures the editing UI for a content class, including attribute labels, descriptions, property groups, validation, and custom editors. ### Usage ```javascript import * as Scrivito from 'scrivito'; Scrivito.provideEditingConfig('ClassName', { // configuration options here }); ``` ### Configuration Example #### Blog Article Editing Configuration ```javascript import * as Scrivito from 'scrivito'; Scrivito.provideEditingConfig('BlogArticle', { title: 'Blog Article', description: 'A blog post with author, date, and rich content', attributes: { title: { title: 'Title', description: 'The main headline of the article', }, author: { title: 'Author Name', }, publishedAt: { title: 'Publication Date', description: 'When this article should be published', }, heroImage: { title: 'Hero Image', description: 'The main image displayed at the top', }, content: { title: 'Article Content', options: { toolbar: ['bold', 'italic', 'link', 'header', 'orderedList', 'bulletList'], }, }, category: { title: 'Category', values: [ { value: 'tech', title: 'Technology' }, { value: 'lifestyle', title: 'Lifestyle' }, { value: 'news', title: 'News' }, { value: 'tutorial', title: 'Tutorial' }, ], }, }, properties: ['title', 'author', 'publishedAt', 'category', 'tags'], propertiesGroups: [ { title: 'SEO', properties: ['metaDescription', 'metaKeywords'], }, { title: 'Related Content', properties: ['relatedArticles'], }, ], titleForContent: (obj) => obj.get('title') || 'Untitled Article', validations: [ (obj) => { if (!obj.get('title')) { return { message: 'Title is required', severity: 'error' }; } }, (obj) => { const title = obj.get('title'); if (title && title.length > 100) { return { message: 'Title should be under 100 characters', severity: 'warning' }; } }, ], }); ``` ``` -------------------------------- ### Scrivito Obj Static Methods Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Methods to access individual CMS objects by ID, path, or permalink. ```APIDOC ## Scrivito.Obj Static Accessors ### Description Access individual CMS objects by ID, path, or permalink. These methods return null if the object does not exist. ### Methods - **get(id)**: Retrieves an object by its unique ID. - **getByPath(path)**: Retrieves an object by its URL path. - **getByPermalink(permalink)**: Retrieves an object by its permalink. - **root()**: Retrieves the root object of the site. - **onSite(siteId)**: Scopes object access to a specific site. ``` -------------------------------- ### Create and Update CMS Objects with Scrivito Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Programmatically create new CMS objects (pages, images, etc.) and update existing ones. Supports creating from files and includes methods for saving, deleting, and copying objects. ```javascript import * as Scrivito from 'scrivito'; // Create a new page const newPage = Scrivito.Obj.create({ _objClass: 'BlogArticle', _path: '/blog/my-new-article', title: 'My New Article', author: 'John Doe', publishedAt: new Date(), category: 'tech', content: '

This is the article content.

', }); ``` ```javascript // Create with reference to another object const imageObj = Scrivito.Obj.get('image-id'); const articleWithImage = Scrivito.Obj.create({ _objClass: 'BlogArticle', title: 'Article with Image', heroImage: imageObj, }); ``` ```javascript // Create binary object from file const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; const uploadedImage = await Scrivito.Obj.createFromFile(file, { _objClass: 'Image', alternativeText: 'Uploaded image description', }); ``` ```javascript // Update an existing object const page = Scrivito.Obj.get('page-id'); page.update({ title: 'Updated Title', lastModified: new Date(), }); ``` ```javascript // Update multiple attributes page.update({ title: 'New Title', metaDescription: 'Updated description', tags: ['javascript', 'tutorial', 'react'], }); ``` ```javascript // Wait for save to complete await page.finishSaving(); console.log('Changes saved successfully'); ``` ```javascript // Delete an object page.delete(); ``` ```javascript // Copy an object const copiedPage = await page.copy(); copiedPage.update({ title: 'Copy of ' + page.get('title') }); ``` -------------------------------- ### Scrivito.load Async Operations Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Utility to convert synchronous Scrivito operations into promises for async data loading. ```APIDOC ## Scrivito.load ### Description Converts synchronous Scrivito operations into promises. Use this to load data outside of React components or when you need explicit async control. ### Parameters - **callback** (function) - Required - A function containing the synchronous Scrivito operations to be executed asynchronously. ### Response - **Promise** - Resolves with the result of the callback function. ``` -------------------------------- ### Register React Components with Scrivito.provideComponent Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Registers a React component to render an Obj or Widget class. Components receive the instance as a prop and can define optional loading states. ```javascript import * as Scrivito from 'scrivito'; // Page component Scrivito.provideComponent('Page', ({ page }) => (

{page.get('title')}

)); // Widget component with loading state Scrivito.provideComponent( 'ImageWidget', ({ widget }) => { const image = widget.get('image'); const link = widget.get('link'); const imageElement = (
{widget.get('caption') && (
{widget.get('caption')}
)}
); if (link) { return {imageElement}; } return imageElement; }, { loading: ({ widget }) => (
Loading image...
), } ); // Column widget with nested content Scrivito.provideComponent('ColumnWidget', ({ widget }) => (
)); ``` -------------------------------- ### Scrivito.connect Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Wraps a React component to automatically handle Scrivito's data loading, re-rendering when CMS data changes. ```APIDOC ## Scrivito.connect ### Description Wraps a React component to automatically handle Scrivito's data loading. Connected components re-render when CMS data changes and can show loading states. ### Parameters - **component** (Function/Class) - Required - The React component to connect. - **options** (Object) - Optional - Configuration object, e.g., { loading: Function } to define a loading state component. ``` -------------------------------- ### Query CMS content with Obj search methods Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Use these methods to filter, order, paginate, and facet CMS objects. These operations are typically performed within an async context using Scrivito.load. ```javascript import * as Scrivito from 'scrivito'; // Get all objects const allPages = Scrivito.Obj.all().take(100); // Basic attribute search const publishedArticles = Scrivito.Obj .where('_objClass', 'equals', 'BlogArticle') .and('publishedAt', 'isLessThanOrEquals', new Date()) .order('publishedAt', 'desc') .take(10); // Full-text search const searchResults = Scrivito.Obj .whereFullTextOf('*', 'contains', 'javascript tutorial') .and('_objClass', 'equals', ['BlogArticle', 'Tutorial']) .take(20); // Chained search with multiple conditions const featuredContent = Scrivito.Obj .where('_objClass', 'equals', 'BlogArticle') .and('category', 'equals', 'tech') .and('featured', 'equals', true) .andNot('status', 'equals', 'draft') .order([['publishedAt', 'desc'], ['title', 'asc']]) .offset(0) .take(5); // Using in async context with load async function fetchLatestArticles(category, limit = 10) { return await Scrivito.load(() => Scrivito.Obj .where('_objClass', 'equals', 'BlogArticle') .and('category', 'equals', category) .and('publishedAt', 'isLessThanOrEquals', new Date()) .order('publishedAt', 'desc') .take(limit) ); } // Faceted search for filtering UI const categoryFacets = Scrivito.Obj .where('_objClass', 'equals', 'BlogArticle') .facet('category', { limit: 10, includeObjs: false }); // Returns: [{ name: 'tech', count: 42 }, { name: 'lifestyle', count: 28 }, ...] // Search within a subtree const childPages = Scrivito.Obj .where('_objClass', 'equals', 'Page') .andIsInsideSubtreeOf(parentPage) .take(); // Count results const articleCount = Scrivito.Obj .where('_objClass', 'equals', 'BlogArticle') .count(); // Iterate with ES6 iterator for (const obj of Scrivito.Obj.all()) { console.log(obj.get('title')); } ``` -------------------------------- ### Configure Editing UI with Scrivito.provideEditingConfig Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Defines the editing interface for content classes, including labels, property groups, and validation logic. ```javascript import * as Scrivito from 'scrivito'; Scrivito.provideEditingConfig('BlogArticle', { title: 'Blog Article', description: 'A blog post with author, date, and rich content', attributes: { title: { title: 'Title', description: 'The main headline of the article', }, author: { title: 'Author Name', }, publishedAt: { title: 'Publication Date', description: 'When this article should be published', }, heroImage: { title: 'Hero Image', description: 'The main image displayed at the top', }, content: { title: 'Article Content', options: { toolbar: ['bold', 'italic', 'link', 'header', 'orderedList', 'bulletList'], }, }, category: { title: 'Category', values: [ { value: 'tech', title: 'Technology' }, { value: 'lifestyle', title: 'Lifestyle' }, { value: 'news', title: 'News' }, { value: 'tutorial', title: 'Tutorial' }, ], }, }, properties: ['title', 'author', 'publishedAt', 'category', 'tags'], propertiesGroups: [ { title: 'SEO', properties: ['metaDescription', 'metaKeywords'], }, { title: 'Related Content', properties: ['relatedArticles'], }, ], titleForContent: (obj) => obj.get('title') || 'Untitled Article', validations: [ (obj) => { if (!obj.get('title')) { return { message: 'Title is required', severity: 'error' }; } }, (obj) => { const title = obj.get('title'); if (title && title.length > 100) { return { message: 'Title should be under 100 characters', severity: 'warning' }; } }, ], }); ``` -------------------------------- ### Define Widget Classes with Scrivito.provideWidgetClass Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Use this method to define reusable content components. Attributes can be defined with various types like html, reference, widgetlist, or enum. ```javascript import * as Scrivito from 'scrivito'; // Text widget const TextWidget = Scrivito.provideWidgetClass('TextWidget', { attributes: { text: 'html', alignment: ['enum', { values: ['left', 'center', 'right'] }], }, }); // Image widget with configurable options const ImageWidget = Scrivito.provideWidgetClass('ImageWidget', { attributes: { image: 'reference', caption: 'string', link: 'link', displayWidth: ['enum', { values: ['full', 'half', 'third'] }], }, }); // Column layout widget with nested widgets const ColumnWidget = Scrivito.provideWidgetClass('ColumnWidget', { attributes: { leftColumn: 'widgetlist', rightColumn: 'widgetlist', columnRatio: ['enum', { values: ['50-50', '33-67', '67-33', '25-75'] }], }, }); // Call-to-action widget const CtaWidget = Scrivito.provideWidgetClass('CtaWidget', { attributes: { headline: 'string', subheadline: 'string', buttonText: 'string', buttonLink: 'link', backgroundColor: 'string', }, }); ``` -------------------------------- ### Scrivito.provideWidgetClass Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Defines a widget class for reusable content components. Widgets can be placed within pages and nested within widget lists. ```APIDOC ## Scrivito.provideWidgetClass ### Description Defines a widget class for reusable content components that can be placed within pages. Widgets are building blocks for page content and can be nested within widget lists. ### Usage ```javascript import * as Scrivito from 'scrivito'; const MyWidget = Scrivito.provideWidgetClass('MyWidget', { attributes: { // attribute definitions here } }); ``` ### Widget Examples #### Text Widget ```javascript import * as Scrivito from 'scrivito'; const TextWidget = Scrivito.provideWidgetClass('TextWidget', { attributes: { text: 'html', alignment: ['enum', { values: ['left', 'center', 'right'] }], }, }); ``` #### Image Widget ```javascript import * as Scrivito from 'scrivito'; const ImageWidget = Scrivito.provideWidgetClass('ImageWidget', { attributes: { image: 'reference', caption: 'string', link: 'link', displayWidth: ['enum', { values: ['full', 'half', 'third'] }], }, }); ``` #### Column Widget ```javascript import * as Scrivito from 'scrivito'; const ColumnWidget = Scrivito.provideWidgetClass('ColumnWidget', { attributes: { leftColumn: 'widgetlist', rightColumn: 'widgetlist', columnRatio: ['enum', { values: ['50-50', '33-67', '67-33', '25-75'] }], }, }); ``` #### Call-to-Action Widget ```javascript import * as Scrivito from 'scrivito'; const CtaWidget = Scrivito.provideWidgetClass('CtaWidget', { attributes: { headline: 'string', subheadline: 'string', buttonText: 'string', buttonLink: 'link', backgroundColor: 'string', }, }); ``` ``` -------------------------------- ### Render optimized images with Scrivito.ImageTag Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt ImageTag handles responsive image rendering, lazy loading, and optimization for binary attributes or Obj references. ```javascript import * as Scrivito from 'scrivito'; function ImageGallery({ images }) { return (
{images.map((imageObj) => (
{/* Basic image rendering from Obj */} {/* With custom width */} {/* Lazy loading for performance */} {/* From widget with binary attribute */} {/* With all HTML img attributes */} console.log('Image loaded')} />
))}
); } ``` -------------------------------- ### Create navigation links with Scrivito.LinkTag Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt LinkTag generates navigation links compatible with Scrivito's SPA routing, supporting internal objects, external URLs, and link attributes. ```javascript import * as Scrivito from 'scrivito'; function Navigation({ page }) { const navItems = page.get('navigationItems') || []; return ( ); } ``` -------------------------------- ### Scrivito.urlFor Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Generates absolute URLs for Objs, Links, or Binaries, useful for canonical tags or sharing. ```APIDOC ## Scrivito.urlFor ### Description Generates a URL for a given Scrivito Obj, Link, or Binary. Supports optional query strings and hash fragments. ### Parameters - **target** (Obj|Link|Binary) - Required - The object to generate a URL for. - **options** (Object) - Optional - An object containing 'query' (string) or 'hash' (string) properties. ### Response - **string** - The absolute URL string. ``` -------------------------------- ### Access current page and site state Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Retrieves information about the active page, URL parameters, and site context. Requires components to be connected to track state changes. ```javascript import * as Scrivito from 'scrivito'; // Get current page const CurrentPageInfo = Scrivito.connect(() => { const page = Scrivito.currentPage(); if (!page) return
No page loaded
; return (

{page.get('title')}

Path: {page.path()}

ID: {page.id()}

); }); // Check if a page is the current page function NavItem({ page }) { const isCurrent = Scrivito.isCurrentPage(page); return ( {page.get('navigationTitle')} ); } // Get current URL parameters const FilteredList = Scrivito.connect(() => { const params = Scrivito.currentPageParams(); const category = params.category || 'all'; const sort = params.sort || 'date'; return (

Filtering by: {category}

Sorting by: {sort}

); }); // Get current site ID (multi-site) const siteId = Scrivito.currentSiteId(); ``` -------------------------------- ### Scrivito.provideObjClass Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Defines a CMS object class (page type) with its attribute schema, allowing the CMS to manage specific content structures. ```APIDOC ## Scrivito.provideObjClass ### Description Defines a CMS object class (page type) with its attribute schema. Object classes represent pages and other content items in the CMS. ### Parameters #### Request Body - **className** (string) - Required - The name of the object class. - **attributes** (object) - Required - A schema definition mapping attribute names to types (e.g., 'string', 'widgetlist', 'date', 'reference', 'html', 'binary'). - **extend** (object) - Optional - An existing class to inherit attributes from. ### Request Example { "className": "Page", "attributes": { "title": "string", "body": "widgetlist" } } ``` -------------------------------- ### Manage User Authentication with Scrivito Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Provides functions to check login status, retrieve current user details, ensure users are logged in, and perform logout operations. Can redirect users after logout. ```javascript import * as Scrivito from 'scrivito'; // Check if user is logged in if (Scrivito.isUserLoggedIn()) { console.log('User is authenticated'); } ``` ```javascript // Get current user details const user = Scrivito.currentUser(); if (user) { console.log('User ID:', user.id()); console.log('User email:', user.email()); console.log('User name:', user.name()); } ``` ```javascript // Require login (redirects to login if not authenticated) Scrivito.ensureUserIsLoggedIn(); ``` ```javascript // With custom return URL Scrivito.ensureUserIsLoggedIn({ returnTo: '/dashboard', }); ``` ```javascript // Logout Scrivito.logout(); ``` ```javascript // Logout with redirect Scrivito.logout('https://www.example.com/goodbye'); ``` ```javascript // Protected component const ProtectedContent = Scrivito.connect(() => { if (!Scrivito.isUserLoggedIn()) { return (

Please log in to view this content.

); } const user = Scrivito.currentUser(); return (

Welcome, {user.name()}!

); }); ``` -------------------------------- ### Page Context Functions Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Functions to access the currently displayed page, navigation state, and site information. ```APIDOC ## Scrivito.currentPage, Scrivito.isCurrentPage, Scrivito.currentPageParams, Scrivito.currentSiteId ### Description Access the currently displayed page, check navigation state, retrieve URL parameters, and get the current site ID. ### Methods - **Scrivito.currentPage()**: Returns the current page object. - **Scrivito.isCurrentPage(page)**: Returns boolean indicating if the provided page is the current one. - **Scrivito.currentPageParams()**: Returns an object containing current URL query parameters. - **Scrivito.currentSiteId()**: Returns the current site ID in multi-site setups. ``` -------------------------------- ### Generate URLs with Scrivito.urlFor Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Generates URLs for Scrivito objects, links, or binaries. Useful for meta tags, canonical URLs, or sharing links. Supports query strings and hashes. ```javascript import * as Scrivito from 'scrivito'; // URL for an Obj const page = Scrivito.Obj.getByPath('/blog/article-1'); const pageUrl = Scrivito.urlFor(page); // => "https://www.example.com/blog/article-1" ``` ```javascript // URL with query string const filteredUrl = Scrivito.urlFor(page, { query: 'page=2&sort=date' }); // => "https://www.example.com/blog/article-1?page=2&sort=date" ``` ```javascript // URL with hash const sectionUrl = Scrivito.urlFor(page, { hash: 'comments' }); // => "https://www.example.com/blog/article-1#comments" ``` ```javascript // URL for a Link object const link = page.get('externalLink'); const linkUrl = Scrivito.urlFor(link); ``` ```javascript // URL for a Binary (image/file download) const image = page.get('heroImage'); const binary = image?.get('blob'); if (binary) { const imageUrl = Scrivito.urlFor(binary); // => "https://assets.scrivito.com/..." } ``` ```javascript // Use in meta tags function PageHead({ page }) { return ( ); } ``` -------------------------------- ### Access individual CMS objects Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Retrieve specific objects by their unique identifiers, paths, or permalinks. These methods return null if the requested object is not found. ```javascript import * as Scrivito from 'scrivito'; // Get by ID const page = Scrivito.Obj.get('abc123def456'); // Get by path const homepage = Scrivito.Obj.getByPath('/'); const aboutPage = Scrivito.Obj.getByPath('/about-us'); // Get by permalink const contactPage = Scrivito.Obj.getByPermalink('contact'); // Get root object const root = Scrivito.Obj.root(); // Multi-site: access objects on specific sites const mainSiteHome = Scrivito.Obj.onSite('main').root(); const blogHome = Scrivito.Obj.onSite('blog').getByPath('/'); // Access all versions across sites const allVersions = page.versionsOnAllSites(); const germanVersion = page.versionOnSite('de'); ``` -------------------------------- ### Connect React components to Scrivito data Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Wraps components to enable automatic data loading and re-rendering. Supports functional components with optional loading states and class-based components. ```javascript import * as Scrivito from 'scrivito'; // Basic connected component const ArticleList = Scrivito.connect(function ArticleList({ category }) { const articles = Scrivito.Obj .where('_objClass', 'equals', 'BlogArticle') .and('category', 'equals', category) .order('publishedAt', 'desc') .take(10); return ( ); }); // With loading component const SearchResults = Scrivito.connect( function SearchResults({ query }) { const results = Scrivito.Obj .whereFullTextOf('*', 'contains', query) .take(20); return (
{results.map((obj) => ( ))}
); }, { loading: ({ query }) => (
Searching for "{query}"...
), } ); // Connected class component class NavigationMenu extends React.Component { static _isScrivitoConnectedComponent = true; render() { const navItems = Scrivito.Obj .where('showInNav', 'equals', true) .order('navOrder', 'asc') .take(10); return ( ); } } export default Scrivito.connect(NavigationMenu); ``` -------------------------------- ### Handle asynchronous data loading with Scrivito.load Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Convert synchronous Scrivito operations into promises. This is required for data fetching outside of React components or for server-side rendering logic. ```javascript import * as Scrivito from 'scrivito'; // Load single object const page = await Scrivito.load(() => Scrivito.Obj.get('page-id')); // Load search results const articles = await Scrivito.load(() => Scrivito.Obj .where('_objClass', 'equals', 'BlogArticle') .order('publishedAt', 'desc') .take(10) ); // Load nested data const pageWithRelated = await Scrivito.load(() => { const page = Scrivito.Obj.get('page-id'); if (!page) return null; return { page, title: page.get('title'), author: page.get('author'), relatedArticles: page.get('relatedArticles'), heroImageUrl: page.get('heroImage')?.contentUrl(), }; }); // Server-side data fetching export async function getStaticProps({ params }) { const page = await Scrivito.load(() => Scrivito.Obj.getByPath(`/${params.slug}`) ); if (!page) { return { notFound: true }; } const data = await Scrivito.load(() => ({ id: page.id(), title: page.get('title'), content: page.get('content'), })); return { props: { data } }; } ``` -------------------------------- ### Scrivito Obj Search API Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Methods for querying CMS content using filters, full-text search, ordering, pagination, and faceted search. ```APIDOC ## Scrivito.Obj Search API ### Description Query CMS content using Scrivito's search API. Supports filtering by attributes, full-text search, ordering, pagination, and faceted search. ### Methods - **all()**: Retrieves all objects. - **where(attribute, operator, value)**: Filters objects based on attribute criteria. - **whereFullTextOf(attribute, operator, value)**: Performs full-text search. - **order(attribute, direction)**: Sorts the results. - **take(limit)**: Limits the number of returned objects. - **offset(index)**: Sets the starting index for pagination. - **facet(attribute, options)**: Performs faceted search for UI filtering. - **count()**: Returns the total number of matching objects. ``` -------------------------------- ### User Authentication API Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Methods for managing visitor authentication and retrieving current user details. ```APIDOC ## User Authentication Methods ### Description Functions to check authentication status, retrieve user data, and handle login/logout flows. ### Methods - **Scrivito.isUserLoggedIn()**: Returns boolean indicating if a user is authenticated. - **Scrivito.currentUser()**: Returns the current user object or null. - **Scrivito.ensureUserIsLoggedIn(options)**: Redirects to login if not authenticated. Accepts 'returnTo' path in options. - **Scrivito.logout(redirectUrl)**: Logs the user out and optionally redirects to the provided URL. ``` -------------------------------- ### Use Data Hook Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Shows how to access the current data scope and perform filtering or transformations on data items within React components. ```javascript import * as Scrivito from 'scrivito'; // Access current data scope function ProductDetails() { const dataScope = Scrivito.useData(); if (dataScope.isEmpty()) { return
No product selected
; } const dataItem = dataScope.dataItem(); if (!dataItem) return null; return (

{dataItem.get('name')}

{dataItem.get('description')}

${dataItem.get('price')}
); } // Filter and transform data function FilteredProductList() { const dataScope = Scrivito.useData(); const filteredScope = dataScope.transform({ filters: { category: 'electronics', inStock: true }, order: [['price', 'asc']], limit: 20, }); const products = filteredScope.take(); return ( ); } ``` -------------------------------- ### Content Manipulation API Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Methods for creating, updating, copying, and deleting CMS objects. ```APIDOC ## Content Manipulation Methods ### Description Programmatic interface for managing CMS content lifecycle. ### Methods - **Scrivito.Obj.create(attributes)**: Creates a new CMS object. - **Scrivito.Obj.createFromFile(file, attributes)**: Creates a binary object from a file input. - **page.update(attributes)**: Updates attributes of an existing object. - **page.finishSaving()**: Returns a promise that resolves when pending changes are saved. - **page.delete()**: Deletes the object. - **page.copy()**: Creates a copy of the object. ``` -------------------------------- ### Render editable content with Scrivito.ContentTag Source: https://context7.com/scrivito/scrivito_sdk_js/llms.txt Use ContentTag to render attributes as editable fields in the UI. It supports various attribute types including strings, HTML, and widget lists. ```javascript import * as Scrivito from 'scrivito'; function ArticlePage({ page }) { return (
{/* String attribute - renders as editable text */}

{/* HTML attribute - renders as rich text with formatting */}
{/* Widget list - renders all widgets in the list */}
{/* With custom HTML attributes */} {/* Pass props to child widgets */} {/* Control rendering of empty attributes */}
); } ```