You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by di...@apache.org on 2025/12/16 13:49:03 UTC
(superset) 01/01: feat(dashboard): add dashboard templates gallery
This is an automated email from the ASF dual-hosted git repository.
diegopucci pushed a commit to branch feat-dashboard-gallery
in repository https://gitbox.apache.org/repos/asf/superset.git
commit c7fc22e7e339a60d4c9d23cc4f6c318f736ebe33
Author: Geidō <60...@users.noreply.github.com>
AuthorDate: Tue Dec 16 13:37:45 2025 +0000
feat(dashboard): add dashboard templates gallery
Implement a Dashboard Templates Gallery feature that allows users to browse,
search, and select dashboard templates, similar to the existing Chart Gallery.
## Backend Changes
- Add template metadata fields to DashboardJSONMetadataSchema (no DB migration required)
- Create DashboardTemplateSchema for API responses
- Add get_templates() method to DashboardDAO with access control filtering
- Create GET /api/v1/dashboard/templates endpoint
## Frontend Changes
- Create DashboardTemplates page with gallery view
- Implement DashboardTemplateGallery component with search and category filtering
- Create DashboardTemplateTile component for template display
- Add TypeScript types and constants
- Update all dashboard creation entry points to redirect to /dashboard/templates:
- Dashboard List page "+ Dashboard" button
- Home page Dashboard Table "+ Dashboard" button
- Empty state "Dashboard" button
- Top navigation "+" dropdown "Dashboard" item
## Key Features
- No database migration required (uses existing json_metadata field)
- Backward compatible (all fields optional)
- Fuzzy search using Fuse.js (same pattern as Chart Gallery)
- Category filtering (Sales, Marketing, Finance, Operations, etc.)
- "Start from blank" tile always appears first
- Access control using existing dashboard permissions
- Responsive grid layout
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <no...@anthropic.com>
---
superset-frontend/src/dashboard/types.ts | 8 +
.../src/features/home/DashboardTable.tsx | 2 +-
superset-frontend/src/features/home/EmptyState.tsx | 2 +-
superset-frontend/src/features/home/RightMenu.tsx | 2 +-
.../src/pages/DashboardList/index.tsx | 2 +-
.../DashboardTemplateGallery.tsx | 274 +++++++++++++++++++++
.../DashboardTemplates/DashboardTemplateTile.tsx | 154 ++++++++++++
.../src/pages/DashboardTemplates/constants.ts | 37 +++
.../src/pages/DashboardTemplates/index.tsx | 73 ++++++
.../src/pages/DashboardTemplates/types.ts | 38 +++
superset-frontend/src/views/routes.tsx | 11 +
superset/daos/dashboard.py | 42 ++++
superset/dashboards/api.py | 73 ++++++
superset/dashboards/schemas.py | 25 ++
14 files changed, 739 insertions(+), 4 deletions(-)
diff --git a/superset-frontend/src/dashboard/types.ts b/superset-frontend/src/dashboard/types.ts
index e1a589acdb..1f1680340c 100644
--- a/superset-frontend/src/dashboard/types.ts
+++ b/superset-frontend/src/dashboard/types.ts
@@ -150,6 +150,14 @@ export type DashboardInfo = {
map_label_colors: JsonObject;
cross_filters_enabled: boolean;
chart_customization_config?: ChartCustomizationItem[];
+ // Template fields
+ is_template?: boolean;
+ is_featured_template?: boolean;
+ template_category?: string;
+ template_thumbnail_url?: string;
+ template_context?: string;
+ template_description?: string;
+ template_tags?: string[];
};
crossFiltersEnabled: boolean;
filterBarOrientation: FilterBarOrientation;
diff --git a/superset-frontend/src/features/home/DashboardTable.tsx b/superset-frontend/src/features/home/DashboardTable.tsx
index efa2256465..eebb84cef1 100644
--- a/superset-frontend/src/features/home/DashboardTable.tsx
+++ b/superset-frontend/src/features/home/DashboardTable.tsx
@@ -200,7 +200,7 @@ function DashboardTable({
name: t('Dashboard'),
buttonStyle: 'secondary',
onClick: () => {
- navigateTo('/dashboard/new', { assign: true });
+ navigateTo('/dashboard/templates', { assign: true });
},
},
{
diff --git a/superset-frontend/src/features/home/EmptyState.tsx b/superset-frontend/src/features/home/EmptyState.tsx
index 35a7050fa1..aa44860480 100644
--- a/superset-frontend/src/features/home/EmptyState.tsx
+++ b/superset-frontend/src/features/home/EmptyState.tsx
@@ -58,7 +58,7 @@ const LABELS = {
const REDIRECTS = {
create: {
[WelcomeTable.Charts]: '/chart/add',
- [WelcomeTable.Dashboards]: '/dashboard/new',
+ [WelcomeTable.Dashboards]: '/dashboard/templates',
[WelcomeTable.SavedQueries]: makeUrl('/sqllab?new=true'),
},
viewAll: {
diff --git a/superset-frontend/src/features/home/RightMenu.tsx b/superset-frontend/src/features/home/RightMenu.tsx
index fda352a0ce..f279559e18 100644
--- a/superset-frontend/src/features/home/RightMenu.tsx
+++ b/superset-frontend/src/features/home/RightMenu.tsx
@@ -217,7 +217,7 @@ const RightMenu = ({
},
{
label: t('Dashboard'),
- url: '/dashboard/new',
+ url: '/dashboard/templates',
icon: (
<Icons.DashboardOutlined data-test={`menu-item-${t('Dashboard')}`} />
),
diff --git a/superset-frontend/src/pages/DashboardList/index.tsx b/superset-frontend/src/pages/DashboardList/index.tsx
index 799055dddb..7b40eade5d 100644
--- a/superset-frontend/src/pages/DashboardList/index.tsx
+++ b/superset-frontend/src/pages/DashboardList/index.tsx
@@ -722,7 +722,7 @@ function DashboardList(props: DashboardListProps) {
name: t('Dashboard'),
buttonStyle: 'primary',
onClick: () => {
- navigateTo('/dashboard/new', { assign: true });
+ navigateTo('/dashboard/templates', { assign: true });
},
});
}
diff --git a/superset-frontend/src/pages/DashboardTemplates/DashboardTemplateGallery.tsx b/superset-frontend/src/pages/DashboardTemplates/DashboardTemplateGallery.tsx
new file mode 100644
index 0000000000..f223ffc480
--- /dev/null
+++ b/superset-frontend/src/pages/DashboardTemplates/DashboardTemplateGallery.tsx
@@ -0,0 +1,274 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import React, { useMemo, useState, useCallback } from 'react';
+import { styled, t } from '@superset-ui/core';
+import Fuse from 'fuse.js';
+import { Input } from 'src/components';
+import Icons from 'src/components/Icons';
+import { DashboardTemplateTile } from './DashboardTemplateTile';
+import {
+ BLANK_TEMPLATE,
+ FEATURED,
+ ALL_TEMPLATES,
+ OTHER_CATEGORY,
+} from './constants';
+import { DashboardTemplate, DashboardTemplateGalleryProps } from './types';
+
+const GalleryLayout = styled.div`
+ display: grid;
+ grid-template-rows: auto minmax(100px, 1fr);
+ grid-template-columns: minmax(14em, auto) 5fr;
+ grid-template-areas:
+ 'sidebar search'
+ 'sidebar main';
+ height: 70vh;
+ overflow: auto;
+ background: ${({ theme }) => theme.colors.grayscale.light4};
+`;
+
+const LeftPane = styled.div`
+ grid-area: sidebar;
+ padding: ${({ theme }) => theme.gridUnit * 4}px;
+ border-right: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
+ overflow-y: auto;
+ background: ${({ theme }) => theme.colors.grayscale.light5};
+`;
+
+const SearchWrapper = styled.div`
+ grid-area: search;
+ padding: ${({ theme }) => theme.gridUnit * 4}px;
+ border-bottom: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
+ background: ${({ theme }) => theme.colors.grayscale.light5};
+`;
+
+const MainContent = styled.div`
+ grid-area: main;
+ padding: ${({ theme }) => theme.gridUnit * 4}px;
+ overflow-y: auto;
+`;
+
+const TileGrid = styled.div`
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: ${({ theme }) => theme.gridUnit * 4}px;
+`;
+
+const Selector = styled.button<{ isSelected: boolean }>`
+ width: 100%;
+ padding: ${({ theme }) => theme.gridUnit * 2}px;
+ margin-bottom: ${({ theme }) => theme.gridUnit}px;
+ border: none;
+ border-radius: ${({ theme }) => theme.gridUnit}px;
+ background: ${({ theme, isSelected }) =>
+ isSelected ? theme.colors.primary.light4 : 'transparent'};
+ color: ${({ theme, isSelected }) =>
+ isSelected ? theme.colors.primary.dark1 : theme.colors.grayscale.dark1};
+ font-weight: ${({ theme, isSelected }) =>
+ isSelected
+ ? theme.typography.weights.bold
+ : theme.typography.weights.normal};
+ text-align: left;
+ cursor: pointer;
+ transition: all 0.2s;
+
+ &:hover {
+ background: ${({ theme }) => theme.colors.primary.light5};
+ }
+`;
+
+const SectionTitle = styled.div`
+ font-weight: ${({ theme }) => theme.typography.weights.bold};
+ font-size: ${({ theme }) => theme.typography.sizes.m}px;
+ margin-bottom: ${({ theme }) => theme.gridUnit * 2}px;
+ margin-top: ${({ theme }) => theme.gridUnit * 3}px;
+ color: ${({ theme }) => theme.colors.grayscale.dark1};
+
+ &:first-child {
+ margin-top: 0;
+ }
+`;
+
+const EmptyState = styled.div`
+ text-align: center;
+ padding: ${({ theme }) => theme.gridUnit * 8}px;
+ color: ${({ theme }) => theme.colors.grayscale.base};
+`;
+
+export const DashboardTemplateGallery: React.FC<
+ DashboardTemplateGalleryProps
+> = ({ templates, loading, onSelectTemplate }) => {
+ const [searchTerm, setSearchTerm] = useState('');
+ const [selectedCategory, setSelectedCategory] = useState(ALL_TEMPLATES);
+
+ // Always prepend "Start from blank" as first item
+ const templatesWithBlank = useMemo(
+ () => [BLANK_TEMPLATE, ...templates],
+ [templates],
+ );
+
+ // Group templates by category
+ const templatesByCategory = useMemo(() => {
+ const grouped: Record<string, DashboardTemplate[]> = {};
+ templates.forEach(template => {
+ const cat = template.template_category || OTHER_CATEGORY;
+ if (!grouped[cat]) {
+ grouped[cat] = [];
+ }
+ grouped[cat].push(template);
+ });
+ return grouped;
+ }, [templates]);
+
+ // Get sorted category list
+ const categories = useMemo(() => {
+ const cats = Object.keys(templatesByCategory).sort();
+ // Move "Other" to end if it exists
+ const otherIndex = cats.indexOf(OTHER_CATEGORY);
+ if (otherIndex > -1) {
+ cats.splice(otherIndex, 1);
+ cats.push(OTHER_CATEGORY);
+ }
+ return cats;
+ }, [templatesByCategory]);
+
+ // Setup Fuse.js for fuzzy search (existing pattern from Chart Gallery)
+ const fuse = useMemo(
+ () =>
+ new Fuse(templates, {
+ keys: [
+ { name: 'dashboard_title', weight: 4 },
+ { name: 'template_description', weight: 1 },
+ ],
+ threshold: 0.3,
+ ignoreLocation: true,
+ }),
+ [templates],
+ );
+
+ // Filter templates based on search and category
+ const filteredTemplates = useMemo(() => {
+ let result = templatesWithBlank;
+
+ // Apply search (skip blank template in search)
+ if (searchTerm) {
+ const searchResults = fuse.search(searchTerm).map(r => r.item);
+ result = [BLANK_TEMPLATE, ...searchResults];
+ }
+
+ // Apply category filter
+ if (selectedCategory === FEATURED) {
+ result = result.filter(t => t.id === null || t.is_featured_template);
+ } else if (selectedCategory !== ALL_TEMPLATES) {
+ result = result.filter(
+ t => t.id === null || t.template_category === selectedCategory,
+ );
+ }
+
+ return result;
+ }, [templatesWithBlank, searchTerm, selectedCategory, fuse]);
+
+ const handleSearchChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ setSearchTerm(e.target.value);
+ },
+ [],
+ );
+
+ const clearSearch = useCallback(() => {
+ setSearchTerm('');
+ }, []);
+
+ if (loading) {
+ return <div>{t('Loading templates...')}</div>;
+ }
+
+ return (
+ <GalleryLayout>
+ {/* Left sidebar with category filters */}
+ <LeftPane>
+ <Selector
+ isSelected={selectedCategory === ALL_TEMPLATES}
+ onClick={() => setSelectedCategory(ALL_TEMPLATES)}
+ >
+ {ALL_TEMPLATES}
+ </Selector>
+
+ <Selector
+ isSelected={selectedCategory === FEATURED}
+ onClick={() => setSelectedCategory(FEATURED)}
+ >
+ <Icons.StarFilled iconSize="m" /> {FEATURED}
+ </Selector>
+
+ {categories.length > 0 && (
+ <>
+ <SectionTitle>{t('Categories')}</SectionTitle>
+ {categories.map(category => (
+ <Selector
+ key={category}
+ isSelected={selectedCategory === category}
+ onClick={() => setSelectedCategory(category)}
+ >
+ {category} ({templatesByCategory[category].length})
+ </Selector>
+ ))}
+ </>
+ )}
+ </LeftPane>
+
+ {/* Search bar */}
+ <SearchWrapper>
+ <Input
+ placeholder={t('Search templates...')}
+ value={searchTerm}
+ onChange={handleSearchChange}
+ prefix={<Icons.SearchOutlined />}
+ suffix={
+ searchTerm && (
+ <Icons.CloseOutlined
+ onClick={clearSearch}
+ style={{ cursor: 'pointer' }}
+ />
+ )
+ }
+ allowClear
+ />
+ </SearchWrapper>
+
+ {/* Main content with template tiles */}
+ <MainContent>
+ <TileGrid>
+ {filteredTemplates.map(template => (
+ <DashboardTemplateTile
+ key={template.uuid}
+ template={template}
+ onClick={onSelectTemplate}
+ />
+ ))}
+ </TileGrid>
+ {filteredTemplates.length === 0 && (
+ <EmptyState>
+ {t('No templates found matching your search.')}
+ </EmptyState>
+ )}
+ </MainContent>
+ </GalleryLayout>
+ );
+};
diff --git a/superset-frontend/src/pages/DashboardTemplates/DashboardTemplateTile.tsx b/superset-frontend/src/pages/DashboardTemplates/DashboardTemplateTile.tsx
new file mode 100644
index 0000000000..01ec8e5acf
--- /dev/null
+++ b/superset-frontend/src/pages/DashboardTemplates/DashboardTemplateTile.tsx
@@ -0,0 +1,154 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import React from 'react';
+import { styled, t } from '@superset-ui/core';
+import { Tag } from 'src/components';
+import Icons from 'src/components/Icons';
+import { DashboardTemplate } from './types';
+
+const Tile = styled.button`
+ display: flex;
+ flex-direction: column;
+ padding: ${({ theme }) => theme.gridUnit * 2}px;
+ cursor: pointer;
+ border: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
+ border-radius: ${({ theme }) => theme.gridUnit}px;
+ background: ${({ theme }) => theme.colors.grayscale.light5};
+ transition: all 0.2s ease;
+
+ &:hover {
+ border-color: ${({ theme }) => theme.colors.primary.base};
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
+ }
+
+ &:focus {
+ outline: 2px solid ${({ theme }) => theme.colors.primary.base};
+ outline-offset: 2px;
+ }
+`;
+
+const ThumbnailWrapper = styled.div`
+ width: 100%;
+ height: 180px;
+ margin-bottom: ${({ theme }) => theme.gridUnit * 2}px;
+ border-radius: ${({ theme }) => theme.gridUnit}px;
+ overflow: hidden;
+ background: ${({ theme }) => theme.colors.grayscale.light3};
+ display: flex;
+ align-items: center;
+ justify-content: center;
+`;
+
+const ThumbnailImage = styled.img`
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+`;
+
+const TitleRow = styled.div`
+ display: flex;
+ align-items: center;
+ gap: ${({ theme }) => theme.gridUnit}px;
+ margin-bottom: ${({ theme }) => theme.gridUnit}px;
+`;
+
+const Title = styled.div`
+ font-weight: ${({ theme }) => theme.typography.weights.bold};
+ font-size: ${({ theme }) => theme.typography.sizes.m}px;
+ color: ${({ theme }) => theme.colors.grayscale.dark1};
+ text-align: left;
+ flex: 1;
+`;
+
+const Description = styled.p`
+ font-size: ${({ theme }) => theme.typography.sizes.s}px;
+ color: ${({ theme }) => theme.colors.grayscale.base};
+ margin-bottom: ${({ theme }) => theme.gridUnit * 2}px;
+ text-align: left;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+`;
+
+const TagsWrapper = styled.div`
+ display: flex;
+ flex-wrap: wrap;
+ gap: ${({ theme }) => theme.gridUnit}px;
+ margin-top: auto;
+`;
+
+interface DashboardTemplateTileProps {
+ template: DashboardTemplate;
+ onClick: (template: DashboardTemplate) => void;
+}
+
+export const DashboardTemplateTile: React.FC<DashboardTemplateTileProps> = ({
+ template,
+ onClick,
+}) => {
+ const isBlank = template.id === null;
+
+ return (
+ <Tile
+ onClick={() => onClick(template)}
+ aria-label={template.dashboard_title}
+ role="button"
+ tabIndex={0}
+ onKeyDown={e => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onClick(template);
+ }
+ }}
+ >
+ <ThumbnailWrapper>
+ {template.template_thumbnail_url ? (
+ <ThumbnailImage
+ src={template.template_thumbnail_url}
+ alt={template.dashboard_title}
+ />
+ ) : (
+ <Icons.DashboardOutlined iconSize="xxl" iconColor="grayscale.light1" />
+ )}
+ </ThumbnailWrapper>
+
+ <TitleRow>
+ <Title>{template.dashboard_title}</Title>
+ {template.is_featured_template && !isBlank && (
+ <Tag>{t('Featured')}</Tag>
+ )}
+ </TitleRow>
+
+ {template.template_description && (
+ <Description>{template.template_description}</Description>
+ )}
+
+ {template.template_tags && template.template_tags.length > 0 && (
+ <TagsWrapper>
+ {template.template_tags.map(tag => (
+ <Tag key={tag}>{tag}</Tag>
+ ))}
+ </TagsWrapper>
+ )}
+ </Tile>
+ );
+};
diff --git a/superset-frontend/src/pages/DashboardTemplates/constants.ts b/superset-frontend/src/pages/DashboardTemplates/constants.ts
new file mode 100644
index 0000000000..deac65e24e
--- /dev/null
+++ b/superset-frontend/src/pages/DashboardTemplates/constants.ts
@@ -0,0 +1,37 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { t } from '@superset-ui/core';
+import { DashboardTemplate } from './types';
+
+export const BLANK_TEMPLATE: DashboardTemplate = {
+ id: null,
+ uuid: 'blank',
+ dashboard_title: t('Start from blank'),
+ template_description: t('Create a new dashboard from scratch'),
+ template_category: null,
+ is_featured_template: false,
+ is_template: false,
+ template_thumbnail_url: null,
+ template_tags: [],
+};
+
+export const FEATURED = t('Featured');
+export const ALL_TEMPLATES = t('All Templates');
+export const OTHER_CATEGORY = t('Other');
diff --git a/superset-frontend/src/pages/DashboardTemplates/index.tsx b/superset-frontend/src/pages/DashboardTemplates/index.tsx
new file mode 100644
index 0000000000..61fe908921
--- /dev/null
+++ b/superset-frontend/src/pages/DashboardTemplates/index.tsx
@@ -0,0 +1,73 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import React, { useState, useEffect } from 'react';
+import { useHistory } from 'react-router-dom';
+import { SupersetClient, t } from '@superset-ui/core';
+import { PageHeaderWithActions } from 'src/components/PageHeaderWithActions';
+import { DashboardTemplateGallery } from './DashboardTemplateGallery';
+import { DashboardTemplate } from './types';
+
+export default function DashboardTemplates() {
+ const [templates, setTemplates] = useState<DashboardTemplate[]>([]);
+ const [loading, setLoading] = useState(true);
+ const history = useHistory();
+
+ useEffect(() => {
+ // Fetch templates from API
+ SupersetClient.get({
+ endpoint: '/api/v1/dashboard/templates',
+ })
+ .then(({ json }) => {
+ setTemplates(json.result);
+ })
+ .catch(error => {
+ console.error('Error fetching templates:', error);
+ })
+ .finally(() => {
+ setLoading(false);
+ });
+ }, []);
+
+ const handleSelectTemplate = (template: DashboardTemplate | null) => {
+ if (template === null || template.id === null) {
+ // "Start from blank" selected - navigate to actual creation endpoint
+ history.push('/dashboard/new');
+ } else {
+ // Navigate to template view (read-only dashboard)
+ history.push(`/superset/dashboard/${template.uuid}/`);
+ }
+ };
+
+ return (
+ <>
+ <PageHeaderWithActions
+ title={t('Dashboard Templates')}
+ subtitle={t(
+ 'Choose a template to get started or create a blank dashboard',
+ )}
+ />
+ <DashboardTemplateGallery
+ templates={templates}
+ loading={loading}
+ onSelectTemplate={handleSelectTemplate}
+ />
+ </>
+ );
+}
diff --git a/superset-frontend/src/pages/DashboardTemplates/types.ts b/superset-frontend/src/pages/DashboardTemplates/types.ts
new file mode 100644
index 0000000000..5b3c028013
--- /dev/null
+++ b/superset-frontend/src/pages/DashboardTemplates/types.ts
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+export interface DashboardTemplate {
+ id: number | null; // null for "Start from blank"
+ uuid: string;
+ dashboard_title: string;
+ slug?: string;
+ template_description?: string;
+ template_category?: string | null;
+ is_featured_template: boolean;
+ is_template: boolean;
+ template_thumbnail_url?: string | null;
+ template_tags: string[];
+ template_context?: string;
+}
+
+export interface DashboardTemplateGalleryProps {
+ templates: DashboardTemplate[];
+ loading: boolean;
+ onSelectTemplate: (template: DashboardTemplate | null) => void;
+}
diff --git a/superset-frontend/src/views/routes.tsx b/superset-frontend/src/views/routes.tsx
index db4fff7214..173d5b10c7 100644
--- a/superset-frontend/src/views/routes.tsx
+++ b/superset-frontend/src/views/routes.tsx
@@ -77,6 +77,13 @@ const Dashboard = lazy(
() => import(/* webpackChunkName: "Dashboard" */ 'src/pages/Dashboard'),
);
+const DashboardTemplates = lazy(
+ () =>
+ import(
+ /* webpackChunkName: "DashboardTemplates" */ 'src/pages/DashboardTemplates'
+ ),
+);
+
const DatabaseList = lazy(
() => import(/* webpackChunkName: "DatabaseList" */ 'src/pages/DatabaseList'),
);
@@ -203,6 +210,10 @@ export const routes: Routes = [
path: '/dashboard/list/',
Component: DashboardList,
},
+ {
+ path: '/dashboard/templates',
+ Component: DashboardTemplates,
+ },
{
path: '/superset/dashboard/:idOrSlug/',
Component: Dashboard,
diff --git a/superset/daos/dashboard.py b/superset/daos/dashboard.py
index 594c1bd0c0..6be5a1885b 100644
--- a/superset/daos/dashboard.py
+++ b/superset/daos/dashboard.py
@@ -105,6 +105,48 @@ class DashboardDAO(BaseDAO[Dashboard]):
def get_charts_for_dashboard(id_or_slug: str) -> list[Slice]:
return DashboardDAO.get_by_id_or_slug(id_or_slug).slices
+ @staticmethod
+ def get_templates() -> list[Dashboard]:
+ """
+ Get all dashboard templates accessible to current user.
+
+ Templates are dashboards with is_template=true in json_metadata.
+ Returns templates ordered by: featured first, then by title.
+
+ Returns:
+ list[Dashboard]: List of template dashboards with access control applied
+ """
+ from sqlalchemy.orm import joinedload
+
+ query = db.session.query(Dashboard).options(
+ joinedload(Dashboard.tags),
+ joinedload(Dashboard.owners),
+ )
+
+ # Apply access filter (existing pattern)
+ query = DashboardDAO.base_filter(
+ "id", SQLAInterface(Dashboard, db.session)
+ ).apply(query, None)
+
+ # Filter to only templates and order
+ dashboards = query.all()
+
+ # Filter in Python (metadata filtering)
+ templates = []
+ for dashboard in dashboards:
+ metadata = json.loads(dashboard.json_metadata or "{}")
+ if metadata.get("is_template", False):
+ # Add sorting metadata as attributes for sorting
+ dashboard._is_featured_template = metadata.get(
+ "is_featured_template", False
+ )
+ templates.append(dashboard)
+
+ # Sort: featured first, then alphabetically by title
+ templates.sort(key=lambda d: (not d._is_featured_template, d.dashboard_title))
+
+ return templates
+
@staticmethod
def get_dashboard_changed_on(id_or_slug_or_dashboard: str | Dashboard) -> datetime:
"""
diff --git a/superset/dashboards/api.py b/superset/dashboards/api.py
index c2cbdcba03..938de382bf 100644
--- a/superset/dashboards/api.py
+++ b/superset/dashboards/api.py
@@ -97,6 +97,7 @@ from superset.dashboards.schemas import (
DashboardPostSchema,
DashboardPutSchema,
DashboardScreenshotPostSchema,
+ DashboardTemplateSchema,
EmbeddedDashboardConfigSchema,
EmbeddedDashboardResponseSchema,
get_delete_ids_schema,
@@ -644,6 +645,78 @@ class DashboardRestApi(CustomTagsOptimizationMixin, BaseSupersetModelRestApi):
except DashboardNotFoundError:
return self.response_404()
+ @expose("/templates", methods=("GET",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.templates",
+ log_to_statsd=False,
+ )
+ @permission_name("read")
+ def templates(self) -> Response:
+ """Get dashboard templates.
+ ---
+ get:
+ summary: Get dashboard templates
+ description: >-
+ Returns a list of dashboard templates available for selection.
+ Templates are dashboards marked with is_template=true in their metadata.
+ responses:
+ 200:
+ description: Dashboard templates list
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ result:
+ type: array
+ items:
+ $ref: '#/components/schemas/DashboardTemplateSchema'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 403:
+ $ref: '#/components/responses/403'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ templates = DashboardDAO.get_templates()
+ return self.response(
+ 200,
+ result=[
+ DashboardTemplateSchema().dump(
+ self._enrich_template_with_metadata(template)
+ )
+ for template in templates
+ ],
+ )
+ except DashboardAccessDeniedError:
+ return self.response_403()
+ except Exception as ex: # pylint: disable=broad-except
+ logger.exception("Error fetching dashboard templates")
+ return self.response_500(message=str(ex))
+
+ def _enrich_template_with_metadata(self, dashboard: Dashboard) -> dict[str, Any]:
+ """Extract template metadata from json_metadata into top-level fields."""
+ metadata = json.loads(dashboard.json_metadata or "{}")
+ return {
+ "id": dashboard.id,
+ "uuid": str(dashboard.uuid),
+ "dashboard_title": dashboard.dashboard_title,
+ "slug": dashboard.slug,
+ "is_template": metadata.get("is_template", False),
+ "is_featured_template": metadata.get("is_featured_template", False),
+ "template_category": metadata.get("template_category"),
+ "template_description": metadata.get("template_description"),
+ "template_thumbnail_url": metadata.get("template_thumbnail_url"),
+ "template_tags": metadata.get("template_tags", []),
+ "template_context": metadata.get("template_context"),
+ }
+
@expose("/", methods=("POST",))
@protect()
@safe
diff --git a/superset/dashboards/schemas.py b/superset/dashboards/schemas.py
index 253bf3dc30..242f2f5aa5 100644
--- a/superset/dashboards/schemas.py
+++ b/superset/dashboards/schemas.py
@@ -168,6 +168,14 @@ class DashboardJSONMetadataSchema(Schema):
remote_id = fields.Integer()
filter_bar_orientation = fields.Str(allow_none=True)
native_filter_migration = fields.Dict()
+ # Template-specific fields
+ is_template = fields.Boolean(allow_none=True)
+ is_featured_template = fields.Boolean(allow_none=True)
+ template_category = fields.String(allow_none=True, validate=Length(0, 255))
+ template_thumbnail_url = fields.String(allow_none=True)
+ template_context = fields.String(allow_none=True)
+ template_description = fields.String(allow_none=True)
+ template_tags = fields.List(fields.String(), allow_none=True)
@pre_load
def remove_show_native_filters( # pylint: disable=unused-argument
@@ -187,6 +195,23 @@ class DashboardJSONMetadataSchema(Schema):
return data
+class DashboardTemplateSchema(Schema):
+ """Lightweight schema for dashboard template listing"""
+
+ id = fields.Integer()
+ uuid = fields.String()
+ dashboard_title = fields.String()
+ slug = fields.String()
+ # Metadata fields (extracted from json_metadata)
+ is_template = fields.Boolean()
+ is_featured_template = fields.Boolean()
+ template_category = fields.String()
+ template_description = fields.String()
+ template_thumbnail_url = fields.String()
+ template_tags = fields.List(fields.String())
+ template_context = fields.String()
+
+
class UserSchema(Schema):
id = fields.Int()
username = fields.String()