JSON Layout API

Build dynamic, data-driven layouts with RSL's powerful JSON engine

Getting Started in 4 Minutes

Step 1: Include Required Files

Include Files: • HTML









Step 2: Create Your Layout with Semantic Content Types

The JSON API provides 50+ semantic content types—no need to write raw HTML:

Breakpoint Reference (click to expand)
Breakpoint Min Width Typical Use
xs0px (default)Mobile phones
sm480pxLarge phones
md768pxTablets
lg1024pxLaptops
xl1280pxDesktops
xxl1600pxLarge screens
Layout with Semantic Types: • JavaScript
const myLayout = {
    version: 2,
    layoutId: "my-first-layout",
    breakpoints: {
        xs: 1,    // 1 column on mobile
        md: 3     // 3 columns on desktop
    },
    gap: "1.5rem",
    items: [
        {
            content: {
                type: "card",
                title: "Getting Started",
                body: "Learn the basics of RSL",
                button: { text: "Learn More", variant: "primary" }
            }
        },
        {
            content: {
                type: "card",
                title: "Components",
                body: "Explore 30+ UI components",
                button: { text: "Browse", variant: "outline" }
            }
        },
        {
            content: {
                type: "card",
                title: "Templates",
                body: "Production-ready templates",
                button: { text: "View All", variant: "outline" }
            }
        }
    ]
};

Step 3: Render the Layout

Render to DOM: • HTML

Live Preview

That's it!

You now have a responsive 3-column card grid. No HTML written—just JSON configuration with semantic content types like card, button, heading, accordion, gallery, and more.

Available Content Types

Use semantic types for common patterns, or type: "html" for custom content:

Layout
card, grid, balanced, divider, spacer
Typography
heading, paragraph, text, list, badge
Interactive
button, link, accordion, tabs, modal, tooltip, popover
Media
image, thumbnail, gallery, carousel, video-player, icon, iframe
Data Display
table, smart-table, chart, kpi, gantt, progress, calendar
Forms
select, datepicker, timepicker, filter, star-rating, form
Navigation
navbar, breadcrumb, pagination, sidebar, offcanvas
Feedback
alert, inlayAlert, toast, skeleton, announcements
Specialty
hero, testimonial, pricing-table, iconpicker
Custom / V1
html, slot, component — for anything else

See full schema with all properties for each type

Step 4: Custom HTML When Needed

For custom designs not covered by semantic types, use type: "html":

Mix Semantic + Custom HTML: • JavaScript
items: [
    // Semantic: Built-in card component
    { content: { type: "card", title: "Standard Card", body: "Uses built-in styling" } },

    // Custom: Your own HTML for unique designs
    {
        content: {
            type: "html",
            value: `
                
42% Conversion Rate
` } }, // Semantic: Built-in accordion component { content: { type: "accordion", items: [...] } } ]

Core API Methods

RSL.JSONLayout.renderLayout(container, config)

Renders a layout from JSON configuration into a DOM container.

Parameters:

container (string | HTMLElement)
CSS selector or DOM element where the layout will be rendered
config (Object)
JSON layout configuration object (see schema reference)

Returns:

HTMLElement - The created layout element

Example:

Code Example: • JavaScript
const layout = RSL.JSONLayout.renderLayout('#app', {
    version: 2,
    layoutId: "dashboard",
    breakpoints: { xs: 1, md: 2, lg: 4 },
    items: [
        { content: { type: "card", title: "Widget 1", body: "..." } },
        { content: { type: "card", title: "Widget 2", body: "..." } }
    ]
});
RSL.JSONLayout.buildFromDOM(container)

Extracts JSON configuration from an existing HTML layout.

Parameters:

container (string | HTMLElement)
Container element containing a .slot-layout

Returns:

Object - JSON layout configuration

Example:

Code Example: • JavaScript
// Extract JSON from existing layout
const config = RSL.JSONLayout.buildFromDOM('#my-layout');

// Save to database
await fetch('/api/save-layout', {
    method: 'POST',
    body: JSON.stringify(config)
});

buildFromDOM vs convertHTMLtoJSON

buildFromDOM(container) — Extracts JSON from an existing .slot-layout element inside a container. Best for extracting layouts you've already rendered.

convertHTMLtoJSON(source) — Converts any HTML string, element, or full document to JSON. More flexible—works with HTML strings, can parse full pages, and finds multiple layouts. Best for importing HTML from external sources or converting entire pages.

State Management (Optional)

The StateManager module provides undo/redo history, named presets, and import/export functionality. It's optional—use it when you need users to save, share, or restore layout configurations. Included in the same layout-json-engine-v2.js file.

RSL.StateManager.savePreset(name, description)

Saves current layout state as a named preset.

Parameters:

name (string)
Unique name for the preset
description (string, optional)
Optional description of the preset

Example:

Code Example: • JavaScript
RSL.StateManager.savePreset('My Dashboard', 'Custom layout for analytics');
RSL.StateManager.loadPreset(name)

Loads a previously saved preset by name.

Parameters:

name (string)
Name of the preset to load

Returns:

boolean - Success status

Example:

Code Example: • JavaScript
RSL.StateManager.loadPreset('My Dashboard');
RSL.StateManager.toJSON(options)

Exports current layout state (and optionally schema) as JSON.

Parameters:

options.includeSchema (boolean)
Include full layout schema (default: false)
options.container (string | HTMLElement)
Container to extract schema from (required if includeSchema is true)

Example:

Code Example: • JavaScript
// Export full layout (schema + state)
const fullExport = RSL.StateManager.toJSON({
    includeSchema: true,
    container: '#app'
});

// Save to file or send to server
const json = JSON.stringify(fullExport, null, 2);
localStorage.setItem('my-layout', json);

Validation & Error Handling

Validate your JSON configuration before rendering to catch errors early:

RSL.JSONLayout.validateSchema(config)

Validates a JSON layout configuration and returns errors/warnings.

Returns:

{ valid: boolean, errors: string[], warnings: string[] }

Example:

Validation Example: • JavaScript
const config = {
    version: 2,
    layoutId: "my-layout",
    breakpoints: { xs: 1, md: 3 },
    items: [{ content: { type: "card", title: "Test" } }]
};

// Validate before rendering
const result = RSL.JSONLayout.validateSchema(config);

if (!result.valid) {
    console.error('Layout errors:', result.errors);
    // Handle errors - show user message, etc.
} else {
    // Safe to render
    RSL.JSONLayout.renderLayout('#container', config);
}

// Warnings don't prevent rendering but indicate potential issues
if (result.warnings.length > 0) {
    console.warn('Layout warnings:', result.warnings);
}

Real-World Code Examples

Example 1: Database-Driven Page

Code Example: • JavaScript
// Backend API endpoint (Node.js + Express)
app.get('/api/page/:pageId', async (req, res) => {
    const page = await db.query(
        'SELECT layout_json FROM pages WHERE id = ?',
        [req.params.pageId]
    );
    res.json(page.layout_json);
});

// Frontend
async function loadPage(pageId) {
    const layout = await fetch(`/api/page/${pageId}`).then(r => r.json());
    RSL.JSONLayout.renderLayout('#content', layout);
}

Example 2: User Dashboard with Presets

Code Example: • JavaScript
// Let users save custom dashboard layouts
function saveDashboard() {
    const layoutName = prompt('Name your dashboard layout:');
    if (layoutName) {
        RSL.StateManager.savePreset(layoutName);
        alert('Dashboard saved!');
    }
}

// On page load, restore user's last used dashboard
const savedPresets = RSL.StateManager.getPresetNames();
if (savedPresets.length > 0) {
    // Load first preset
    RSL.StateManager.loadPreset(savedPresets[0]);
}

Example 3: A/B Testing Layouts

Code Example: • JavaScript
// Show different layout variants to different users
const variants = {
    A: { /* layout with hero banner */ },
    B: { /* layout with video hero */ },
    C: { /* layout with carousel */ }
};

// Randomly assign variant
const variant = ['A', 'B', 'C'][Math.floor(Math.random() * 3)];

// Track which variant user sees
analytics.track('layout_variant_shown', { variant });

// Render the variant
RSL.JSONLayout.renderLayout('#hero', variants[variant]);

Example 4: Dynamic Content from API

Code Example: • JavaScript
// Fetch products from API
const products = await fetch('/api/products').then(r => r.json());

// Create layout dynamically with semantic card type
const productLayout = {
    version: 2,
    layoutId: "products-grid",
    breakpoints: { xs: 1, sm: 2, lg: 4 },
    gap: "2rem",
    items: products.map(product => ({
        content: {
            type: "card",
            image: product.image,
            title: product.name,
            price: `$${product.price}`,
            button: { text: "Add to Cart", variant: "primary" }
        }
    }))
};

RSL.JSONLayout.renderLayout('#products', productLayout);

Example 5: Multi-Site Management

Code Example: • JavaScript
// Admin creates a layout template
const template = RSL.JSONLayout.buildFromDOM('#template-preview');

// Deploy to multiple client sites
const sites = ['site1.com', 'site2.com', 'site3.com'];

for (const site of sites) {
    await fetch(`https://${site}/api/update-layout`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            section: 'homepage-hero',
            layout: template
        })
    });
}

console.log('Layout deployed to all sites!');

Common Use Cases

Analytics Dashboards

Let users customize which metrics they see, resize widgets, and save multiple dashboard layouts for different purposes.

Code Example: • JavaScript
// User customizes their analytics dashboard
RSL.StateManager.savePreset('Sales Dashboard');
RSL.StateManager.savePreset('Traffic Dashboard');
RSL.StateManager.savePreset('Conversion Dashboard');

E-Commerce Product Grids

Store managers can rearrange featured products, test different layouts, and schedule layout changes for promotions.

Code Example: • JavaScript
// Fetch products and render in customizable grid
const products = await getProducts();
const layout = generateProductGrid(products);
RSL.JSONLayout.renderLayout('#products', layout);

News & Media Sites

Editors can control homepage layout without developer intervention. A/B test article placement to optimize engagement.

Code Example: • JavaScript
// CMS stores layout for each page section
const heroLayout = await cms.getLayout('homepage-hero');
const articlesLayout = await cms.getLayout('homepage-articles');
RSL.JSONLayout.renderLayout('#hero', heroLayout);
RSL.JSONLayout.renderLayout('#articles', articlesLayout);

Page Builders & Visual Editors

Build drag-and-drop editors where users design pages visually, then export/publish as JSON.

Code Example: • JavaScript
// After user edits layout visually
const finalLayout = RSL.JSONLayout.buildFromDOM('#editor');

// Publish to production
await publishPage(finalLayout);

Multi-Tenant SaaS Applications

Each tenant/customer can have their own custom layout while sharing the same codebase.

Code Example: • JavaScript
// Load tenant-specific layout
const tenantId = getCurrentTenant();
const layout = await fetch(`/api/tenant/${tenantId}/layout`).then(r => r.json());
RSL.JSONLayout.renderLayout('#app', layout);

Learning Management Systems

Instructors arrange course modules and content. Students can customize their learning dashboard.

Code Example: • JavaScript
// Student customizes their course dashboard
const studentLayout = RSL.StateManager.toJSON({ includeSchema: true });
await saveStudentPreferences(studentId, studentLayout);

The Pattern

All these use cases follow the same pattern:

  1. Store layouts as JSON (database, API, localStorage)
  2. Fetch/load the JSON when needed
  3. Render with RSL using renderLayout()
  4. Save changes back to storage when user customizes