# section URL: /api/core/section/ Section: core -------------------------------------------------------------------------------- section - Bengal window.BENGAL_THEME_DEFAULTS = { appearance: 'dark', palette: 'snow-lynx' }; // Progressive Enhancement System Configuration window.Bengal = window.Bengal || {}; window.Bengal.enhanceBaseUrl = '/bengal/assets/js/enhancements'; window.Bengal.watchDom = true; window.Bengal.debug = false; (function () { try { var defaults = window.BENGAL_THEME_DEFAULTS || { appearance: 'system', palette: '' }; var defaultAppearance = defaults.appearance; if (defaultAppearance === 'system') { defaultAppearance = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; } var storedTheme = localStorage.getItem('bengal-theme'); var storedPalette = localStorage.getItem('bengal-palette'); var theme = storedTheme ? (storedTheme === 'system' ? defaultAppearance : storedTheme) : defaultAppearance; var palette = storedPalette ?? defaults.palette; document.documentElement.setAttribute('data-theme', theme); if (palette) { document.documentElement.setAttribute('data-palette', palette); } } catch (e) { document.documentElement.setAttribute('data-theme', 'light'); } })(); Skip to main content Magnifying Glass ESC Recent Clear Magnifying Glass No results for "" Try different keywords or check your spelling Start typing to search... ↑↓ Navigate ↵ Open ESC Close Powered by Lunr ᓚᘏᗢ Documentation Info About Arrow Clockwise Get Started Note Tutorials File Text Content Palette Theming Settings Building Starburst Extending Bookmark Reference Learning Tracks Releases Dev GitHub API Reference bengal CLI Magnifying Glass Search ⌘K Palette Appearance Chevron Down Mode Monitor System Sun Light Moon Dark Palette Snow Lynx Brown Bengal Silver Bengal Charcoal Bengal Blue Bengal List ᓚᘏᗢ Magnifying Glass Search X Close Documentation Info About Arrow Clockwise Get Started Note Tutorials File Text Content Palette Theming Settings Building Starburst Extending Bookmark Reference Learning Tracks Releases Dev GitHub API Reference bengal CLI Palette Appearance Chevron Down Mode Monitor System Sun Light Moon Dark Palette Snow Lynx Brown Bengal Silver Bengal Charcoal Bengal Blue Bengal API Reference __main__ bengal Caret Right Folder Analysis community_detection graph_analysis graph_reporting graph_visualizer knowledge_graph link_suggestions link_types page_rank path_analysis performance_advisor results Caret Right Folder Assets manifest pipeline Caret Right Folder Autodoc base config docstring_parser utils virtual_orchestrator Caret Right Folder Extractors cli openapi python Caret Right Folder Models cli common openapi python Caret Right Folder Cache asset_dependency_map cache_store cacheable compression dependency_tracker page_discovery_cache query_index query_index_registry taxonomy_index utils Caret Right Folder Build Cache autodoc_tracking core file_tracking fingerprint parsed_content_cache rendered_output_cache taxonomy_index_mixin validation_cache Caret Right Folder Indexes author_index category_index date_range_index section_index Caret Right Folder Cli __main__ base site_templates utils Caret Right Folder Commands assets build clean collections config debug explain fix health init perf project serve site skeleton sources theme utils validate Caret Right Folder Graph __main__ bridges communities orphans pagerank report suggest Caret Right Folder New config presets scaffolds site wizard Caret Right Folder Helpers cli_app_loader cli_output config_validation error_handling menu_config metadata progress site_loader traceback validation Caret Right Folder Skeleton hydrator schema Caret Right Folder Templates base registry Caret Right Folder Blog template Caret Right Folder Changelog template Caret Right Folder Default template Caret Right Folder Docs template Caret Right Folder Landing template Caret Right Folder Portfolio template Caret Right Folder Resume template Caret Right Folder Collections errors loader schemas validator Caret Right Folder Config defaults deprecation directory_loader env_overrides environment feature_mappings hash loader merge origin_tracker validators Caret Right Folder Content Layer entry loaders manager source Caret Right Folder Sources github local notion rest Caret Right Folder Content Types base registry strategies Caret Right Folder Core build_context cascade_engine menu section theme Caret Right Folder Asset asset_core css_transforms Caret Right Folder Page computed content metadata navigation operations page_core proxy relationships utils Caret Right Folder Site core data discovery factories page_caches properties section_registry theme Caret Right Folder Debug base config_inspector content_migrator delta_analyzer dependency_visualizer explainer incremental_debugger models reporter shortcode_sandbox Caret Right Folder Discovery asset_discovery content_discovery Caret Right Folder Fonts downloader generator Caret Right Folder Health autofix base health_check report Caret Right Folder Linkcheck async_checker ignore_policy internal_checker models orchestrator Caret Right Folder Validators anchors assets cache config connectivity cross_ref fonts links menu navigation output performance rendering rss sitemap taxonomy tracks Caret Right Folder Directives analysis checkers constants Caret Right Folder Orchestration asset content full_to_incremental incremental menu postprocess related_posts render section static streaming taxonomy Caret Right Folder Postprocess html_output redirects rss sitemap special_pages Caret Right Folder Output Formats index_generator json_generator llm_generator lunr_index_generator txt_generator utils Caret Right Folder Rendering api_doc_enhancer asset_extractor errors jinja_utils link_transformer link_validator pygments_cache renderer template_context template_profiler validator Caret Right Folder Parsers base factory mistune native_html pygments_patch python_markdown Caret Right Folder Pipeline core output thread_local toc transforms Caret Right Folder Plugins badges cross_references inline_icon term variable_substitution Caret Right Folder Directives _icons admonitions badge base button cache cards checklist code_tabs container contracts data_table dropdown embed errors example_label fenced figure glossary icon include list_table literalinclude marimo navigation options rubric steps tabs target term terminal tokens utils validator video Caret Right Folder Template Engine asset_url core environment manifest menu url_helpers Caret Right Folder Template Functions advanced_collections advanced_strings autodoc collections content crossref data dates debug files get_page i18n icons images math_functions navigation pagination_helpers seo strings tables taxonomies theme urls Caret Right Folder Server build_handler component_preview constants dev_server live_reload pid_manager reload_controller request_handler request_logger resource_manager utils Caret Right Folder Services validation Caret Right Folder Themes config Caret Right Folder Utils atomic_write autodoc build_context build_stats build_summary cli_output css_minifier dates dotdict error_handlers file_io file_lock hashing incremental_constants js_bundler live_progress logger metadata observability page_initializer pagination path_resolver paths performance_collector performance_report profile progress retry rich_console sections swizzle text theme_registry theme_resolution thread_local traceback_config traceback_renderer url_normalization url_strategy API Reference Core ᗢ Caret Down Link Copy URL External Open LLM text Copy Copy LLM text Share with AI Ask Claude Ask ChatGPT Ask Gemini Ask Copilot Module core.section Section representation for organizing pages into hierarchical groups. Sections represent directories in the content tree and provide navigation, sorting, and hierarchical query interfaces. Sections can be nested and maintain parent-child relationships. Each section can have an index page and contains both regular pages and subsections. Key Concepts: Hierarchy: Sections form a tree structure with parent-child relationships Index pages: Special pages (_index.md or index.md) that represent the section Weight-based sorting: Pages and subsections sorted by weight metadata Hashability: Sections are hashable by path for set operations Related Modules: bengal.core.page: Page objects contained within sections bengal.core.site: Site container that manages all sections bengal.orchestration.content: Content discovery that builds section hierarchy See Also: bengal/core/section.py: Section class for section representation View source 2 Classes Classes WeightedPage dataclass 1 Caret Right Attributes Name Type Description page Page weight float title_lower str Internal Methods 1 Caret Right __lt__ 1 bool Caret Right def __lt__(self, other: WeightedPage) -> bool Parameters 1 other WeightedPage Returns bool Section dataclass Represents a folder or logical grouping of pages. HASHABILITY: ============ Sections are hashable … 30 Caret Right Represents a folder or logical grouping of pages. HASHABILITY: ============ Sections are hashable based on their path (or name for virtual sections), allowing them to be stored in sets and used as dictionary keys. This enables: Fast membership tests and lookups Type-safe Set[Section] collections Set operations for section analysis Two sections with the same path are considered equal. The hash is stable throughout the section lifecycle because path is immutable. VIRTUAL SECTIONS: ================= Virtual sections represent API documentation or other dynamically-generated content that doesn't have a corresponding directory on disk. Virtual sections: Have _virtual=True and path=None Are discovered via VirtualAutodocOrchestrator during build Work with menu system via name-based lookups Don't write intermediate markdown files Attributes Name Type Description name str Section name path Path | None Path to the section directory (None for virtual sections) pages list[Page] List of pages in this section subsections list[Section] Child sections metadata dict[str, Any] Section-level metadata index_page Page | None Optional index page for the section parent Section | None Parent section (if nested) _virtual bool True if this is a virtual section (no disk directory) _relative_url_override str | None _site Any | None Methods 27 Tag is_virtual property Check if this is a virtual section (no disk directory). Virtual sections are u… bool Caret Right def is_virtual(self) -> bool Check if this is a virtual section (no disk directory). Virtual sections are used for: API documentation generated from Python source code Dynamically-generated content from external sources Content that doesn't have a corresponding content/ directory Returns bool — True if this section is virtual (not backed by a disk directory) Tag slug property URL-friendly identifier for this section. For virtual sections, uses the name … str Caret Right def slug(self) -> str URL-friendly identifier for this section. For virtual sections, uses the name directly. For physical sections, uses the directory name. Returns str — Section slug (e.g., "api", "core", "bengal-core") Tag title property Get section title from metadata or generate from name. str Caret Right def title(self) -> str Get section title from metadata or generate from name. Returns str Tag icon property Get section icon from index page metadata (cached). Icons can be specified in … str | None Caret Right def icon(self) -> str | None Get section icon from index page metadata (cached). Icons can be specified in a section's _index.md frontmatter: --- title: API Reference icon: book --- The icon name should match a Phosphor icon in the icon library (e.g., 'book', 'folder', 'terminal', 'code'). Returns str | None — Icon name string, or None if no icon is specified Tag hierarchy property Get the full hierarchy path of this section. list[str] Caret Right def hierarchy(self) -> list[str] Get the full hierarchy path of this section. Returns list[str] — List of section names from root to this section Tag depth property Get the depth of this section in the hierarchy. int Caret Right def depth(self) -> int Get the depth of this section in the hierarchy. Returns int Tag root property Get the root section of this section's hierarchy. Section Caret Right def root(self) -> Section Get the root section of this section's hierarchy. Returns Section — The topmost ancestor section Tag regular_pages property Get only regular pages (non-sections) in this section. list[Page] Caret Right def regular_pages(self) -> list[Page] Get only regular pages (non-sections) in this section. Returns list[Page] — List of regular Page objects (excludes subsections) Tag sections property Get immediate child sections. list[Section] Caret Right def sections(self) -> list[Section] Get immediate child sections. Returns list[Section] — List of child Section objects Tag sorted_pages property Get pages sorted by weight (ascending), then by title (CACHED). This property … list[Page] Caret Right def sorted_pages(self) -> list[Page] Get pages sorted by weight (ascending), then by title (CACHED). This property is cached after first access for O(1) subsequent lookups. The sort is computed once and reused across all template renders. Pages without a weight field are treated as having weight=float('inf') and appear at the end of the sorted list, after all weighted pages. Lower weights appear first in the list. Pages with equal weight are sorted alphabetically by title. Performance: First access: O(n log n) where n = number of pages Subsequent accesses: O(1) cached lookup Memory cost: O(n) to store sorted list Returns list[Page] — List of pages sorted by weight, then title Tag sorted_subsections property Get subsections sorted by weight (ascending), then by title (CACHED). This pro… list[Section] Caret Right def sorted_subsections(self) -> list[Section] Get subsections sorted by weight (ascending), then by title (CACHED). This property is cached after first access for O(1) subsequent lookups. The sort is computed once and reused across all template renders. Subsections without a weight field in their index page metadata are treated as having weight=999999 (appear at end). Lower weights appear first. Performance: First access: O(m log m) where m = number of subsections Subsequent accesses: O(1) cached lookup Memory cost: O(m) to store sorted list Returns list[Section] — List of subsections sorted by weight, then title Tag subsection_index_urls property Get set of URLs for all subsection index pages (CACHED). This pre-computed set… set[str] Caret Right def subsection_index_urls(self) -> set[str] Get set of URLs for all subsection index pages (CACHED). This pre-computed set enables O(1) membership checks for determining if a page is a subsection index. Used in navigation templates to avoid showing subsection indices twice (once as page, once as subsection link). Performance: First access: O(m) where m = number of subsections Subsequent lookups: O(1) set membership check Memory cost: O(m) URLs Returns set[str] — Set of URL strings for subsection index pages Tag has_nav_children property Check if this section has navigable children (CACHED). A section has navigable… bool Caret Right def has_nav_children(self) -> bool Check if this section has navigable children (CACHED). A section has navigable children if it contains either: Regular pages (excluding the index page itself) Subsections This property is used by navigation templates to determine whether to render a section as an expandable group (with toggle button) or as a simple link. Sections without children should not show an expand/collapse toggle since there's nothing to expand. Performance: First access: O(1) - uses cached sorted_pages/sorted_subsections Subsequent accesses: O(1) cached lookup Returns bool — True if section has pages or subsections to display in nav Tag regular_pages_recursive property Get all regular pages recursively (including from subsections). list[Page] Caret Right def regular_pages_recursive(self) -> list[Page] Get all regular pages recursively (including from subsections). Returns list[Page] — List of all descendant regular pages Tag relative_url property Get relative URL without baseurl (for comparisons). This is the identity URL -… str Caret Right def relative_url(self) -> str Get relative URL without baseurl (for comparisons). This is the identity URL - use for comparisons, menu activation, etc. Always returns a relative path without baseurl. For virtual sections, uses the _relative_url_override set during creation. Virtual sections MUST have explicit URLs - they never fall back to construction. Returns str Tag url property Get URL with baseurl applied (cached after first access). This is the primary … str Caret Right def url(self) -> str Get URL with baseurl applied (cached after first access). This is the primary URL property for templates - automatically includes baseurl when available. Use .relative_url for comparisons. Returns str — URL path with baseurl prepended (if configured) Tag permalink property Alias for url (for backward compatibility). Both url and permalink now return … str Caret Right def permalink(self) -> str Alias for url (for backward compatibility). Both url and permalink now return the same value (with baseurl). Use .relative_url for comparisons. Returns str create_virtual classmethod Create a virtual section for dynamically-generated content. Virtual sections a… 4 Section Caret Right def create_virtual(cls, name: str, relative_url: str, title: str | None = None, metadata: dict[str, Any] | None = None) -> Section Create a virtual section for dynamically-generated content. Virtual sections are not backed by a disk directory but integrate with the site's section hierarchy, navigation, and menu system. Parameters 4 name str Section name (used for lookups, e.g., "api") relative_url str URL for this section (e.g., "/api/") title str | None Display title (defaults to titlecase of name) metadata dict[str, Any] | None Optional section metadata Returns Section — A new virtual Section instance add_page Add a page to this section. 1 None Caret Right def add_page(self, page: Page) -> None Add a page to this section. Parameters 1 page Page Page to add add_subsection Add a subsection to this section. 1 None Caret Right def add_subsection(self, section: Section) -> None Add a subsection to this section. Parameters 1 section Section Child section to add sort_children_by_weight Sort pages and subsections in this section by weight, then by title. This modi… 0 None Caret Right def sort_children_by_weight(self) -> None Sort pages and subsections in this section by weight, then by title. This modifies the pages and subsections lists in place. Pages/sections without a weight field are treated as having weight=float('inf'), so they appear at the end (after all weighted items). Lower weights appear first in the sorted lists. This is typically called after content discovery is complete. needs_auto_index Check if this section needs an auto-generated index page. 0 bool Caret Right def needs_auto_index(self) -> bool Check if this section needs an auto-generated index page. Returns bool — True if section needs auto-generated index (no explicit _index.md) has_index Check if section has a valid index page. 0 bool Caret Right def has_index(self) -> bool Check if section has a valid index page. Returns bool — True if section has an index page (explicit or auto-generated) get_all_pages Get all pages in this section. 1 list[Page] Caret Right def get_all_pages(self, recursive: bool = True) -> list[Page] Get all pages in this section. Parameters 1 recursive bool If True, include pages from subsections Returns list[Page] — List of all pages aggregate_content Aggregate content from all pages in this section. 0 dict[str, Any] Caret Right def aggregate_content(self) -> dict[str, Any] Aggregate content from all pages in this section. Returns dict[str, Any] — Dictionary with aggregated content information apply_section_template Apply a section template to generate a section index page. 1 str Caret Right def apply_section_template(self, template_engine: Any) -> str Apply a section template to generate a section index page. Parameters 1 template_engine Any Template engine instance Returns str — Rendered HTML for the section index walk Iteratively walk through all sections in the hierarchy. 0 list[Section] Caret Right def walk(self) -> list[Section] Iteratively walk through all sections in the hierarchy. Returns list[Section] — List of all sections (self and descendants) Internal Methods 3 Caret Right __hash__ Hash based on section path (or name for virtual sections) for stable identity. … 0 int Caret Right def __hash__(self) -> int Hash based on section path (or name for virtual sections) for stable identity. The hash is computed from the section's path, which is immutable throughout the section lifecycle. This allows sections to be stored in sets and used as dictionary keys. For virtual sections (path=None), uses the name and _relative_url_override for hashing to ensure stable identity. Returns int — Integer hash of the section path or name __eq__ Sections are equal if they have the same path (or name+URL for virtual). Equal… 1 bool Caret Right def __eq__(self, other: Any) -> bool Sections are equal if they have the same path (or name+URL for virtual). Equality is based on path only, not on pages or other mutable fields. This means two Section objects representing the same directory are considered equal, even if their contents differ. For virtual sections (path=None), equality is based on name and URL. Parameters 1 other Any Object to compare with Returns bool — True if other is a Section with the same path __repr__ 0 str Caret Right def __repr__(self) -> str Returns str ← Previous menu Next → theme List © 2025 Bengal ᓚᘏᗢ window.BENGAL_LAZY_ASSETS = { tabulator: '/bengal/assets/js/tabulator.min.js', dataTable: '/bengal/assets/js/data-table.js', mermaidToolbar: '/bengal/assets/js/mermaid-toolbar.9de5abba.js', mermaidTheme: '/bengal/assets/js/mermaid-theme.344822c5.js', graphMinimap: '/bengal/assets/js/graph-minimap.cc7e42e3.js', graphContextual: '/bengal/assets/js/graph-contextual.440e59c6.js' }; window.BENGAL_ICONS = { close: '/bengal/assets/icons/close.911d4fe1.svg', enlarge: '/bengal/assets/icons/enlarge.652035e5.svg', copy: '/bengal/assets/icons/copy.3d56e945.svg', 'download-svg': '/bengal/assets/icons/download.04f07e1b.svg', 'download-png': '/bengal/assets/icons/image.c34dfd40.svg', 'zoom-in': '/bengal/assets/icons/zoom-in.237b4a83.svg', 'zoom-out': '/bengal/assets/icons/zoom-out.38857c77.svg', reset: '/bengal/assets/icons/reset.d26dba29.svg' }; Arrow Up X -------------------------------------------------------------------------------- Metadata: - Author: lbliii - Word Count: 3050 - Reading Time: 15 minutes