# renderer URL: /api/rendering/renderer/ Section: rendering -------------------------------------------------------------------------------- renderer - 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 Rendering ᗢ 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 rendering.renderer Renderer for converting pages to final HTML output. Handles individual page rendering using templates, markdown processing, and content transformation. Integrates with template engine for Jinja2 rendering and provides error handling with graceful degradation. Key Concepts: Template rendering: Jinja2 template rendering with page context Markdown processing: Markdown to HTML conversion Content transformation: Link rewriting, image processing, etc. Error handling: Graceful error handling with error pages Related Modules: bengal.rendering.template_engine: Template engine for Jinja2 rendering bengal.rendering.parsers.mistune: Markdown parser bengal.rendering.link_transformer: Link transformation logic See Also: bengal/rendering/renderer.py: Renderer class for rendering logic plan/active/rfc-template-performance-optimization.md: Performance RFC View source 1 Class Classes Renderer Renders individual pages using templates and content processing. Handles template rendering, conte… 8 Caret Right Renders individual pages using templates and content processing. Handles template rendering, content processing (H1 stripping), and error collection. Integrates with template engine for Jinja2 rendering and provides graceful error handling. Creation: Direct instantiation: Renderer(template_engine, build_stats=None) Created by RenderingPipeline for page rendering Requires TemplateEngine instance Attributes Name Type Description template_engine — TemplateEngine instance for Jinja2 rendering site — Site instance (accessed via template_engine.site) build_stats — Optional BuildStats for error collection Relationships — Uses: TemplateEngine for template rendering - Uses: BuildStats for error collection - Used by: RenderingPipeline for page rendering Thread Safety: Thread-safe. Each thread should have its own Renderer instance. Methods 2 render_content Render raw content (already parsed HTML). Automatically strips the first H1 ta… 1 str Caret Right def render_content(self, content: str) -> str Render raw content (already parsed HTML). Automatically strips the first H1 tag to avoid duplication with the template-rendered title. Parameters 1 content str Parsed HTML content Returns str — Content with first H1 removed render_page Render a complete page with template. Architecture: 1. Builds initial context … 2 str Caret Right def render_page(self, page: Page, content: str | None = None) -> str Render a complete page with template. Architecture: Builds initial context (metadata, TOC, content) Adds specialized context based on page type: Generated pages (tags/archives): Adds filtered posts list Section pages: Adds section-specific posts Root index: Adds top-level pages Renders using Jinja2 template Conflict Prevention: Logic strictly separates "Root Index" (home page) from "Generated Index" (tag pages). Tag pages often have source paths like tags/foo/index.md (is_index_page=True) but must NOT use the root home page logic which overwrites their posts list. Parameters 2 page Page Page to render content str | None Optional pre-rendered content (uses page.parsed_ast if not provided) Returns str — Fully rendered HTML page Internal Methods 6 Caret Right __init__ Initialize the renderer. 2 None Caret Right def __init__(self, template_engine: Any, build_stats: Any = None) -> None Initialize the renderer. Parameters 2 template_engine Any Template engine instance build_stats Any Optional BuildStats object for error collection _strip_first_h1 Remove the first H1 tag from HTML content. This prevents duplication when temp… 1 str Caret Right def _strip_first_h1(self, content: str) -> str Remove the first H1 tag from HTML content. This prevents duplication when templates render {{ page.title }} as H1 and the markdown also contains an H1 heading. Parameters 1 content str HTML content Returns str — Content with first H1 tag removed _add_generated_page_context Add special context variables for generated pages (archives, tags, etc.). 2 None Caret Right def _add_generated_page_context(self, page: Page, context: dict[str, Any]) -> None Add special context variables for generated pages (archives, tags, etc.). Parameters 2 page Page Page being rendered context dict[str, Any] Template context to update _get_template_name Determine which template to use for a page. Priority order: 1. Explicit templa… 1 str Caret Right def _get_template_name(self, page: Page) -> str Determine which template to use for a page. Priority order: Explicit template in frontmatter (template: doc.html) Content type strategy (delegates to strategy.get_template()) Section-based auto-detection (e.g., docs.html, docs/single.html) Default fallback (page.html or index.html) Note: We use a simple, explicit template selection strategy without complex type/kind/layout hierarchies. Parameters 1 page Page Page to get template for Returns str — Template name _template_exists Check if a template exists in any template directory. 1 bool Caret Right def _template_exists(self, template_name: str) -> bool Check if a template exists in any template directory. Parameters 1 template_name str Template filename or path Returns bool — True if template exists, False otherwise _render_fallback Render a fallback HTML page with basic styling. When the main template fails, … 2 str Caret Right def _render_fallback(self, page: Page, content: str) -> str Render a fallback HTML page with basic styling. When the main template fails, we still try to produce a usable page with basic CSS and structure (though without partials/navigation). Parameters 2 page Page Page to render content str Page content Returns str — Fallback HTML page with minimal styling ← Previous pygments_cache Next → rendering 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: 1683 - Reading Time: 8 minutes