# template_context URL: /api/rendering/template_context/ Section: rendering -------------------------------------------------------------------------------- template_context - 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.template_context Template context wrappers for ergonomic URL handling. Wraps Page and Section objects so that .url automatically includes baseurl in templates, making it impossible to forget baseurl in href/src attributes. Provides transparent delegation to wrapped objects while adding baseurl handling. Key Concepts: Auto-baseurl: Automatically applies baseurl to .url property Transparent delegation: All other properties delegate to wrapped object Multiple baseurl formats: Supports path, absolute, file, and S3 URLs Template ergonomics: Simplifies template code by removing baseurl handling Related Modules: bengal.rendering.template_engine: Template engine that uses wrappers bengal.core.page: Page objects being wrapped bengal.core.section: Section objects being wrapped See Also: bengal/rendering/template_context.py: TemplatePageWrapper for page wrapper bengal/rendering/template_context.py: TemplateSectionWrapper for section wrapper View source 3 Classes 1 Function Classes TemplatePageWrapper Wraps Page objects to auto-apply baseurl to .url in templates. Provides transparent wrapper that a… 6 Caret Right Wraps Page objects to auto-apply baseurl to .url in templates. Provides transparent wrapper that automatically applies baseurl to page URLs, making templates ergonomic. All other page properties delegate to the wrapped page object, maintaining full compatibility. Creation: Direct instantiation: TemplatePageWrapper(page, baseurl="") Created by TemplateEngine for template context Requires Page instance and optional baseurl Attributes Name Type Description _page — Wrapped Page object _baseurl — Base URL from site config (can be empty, path-only, or absolute) Relationships — Uses: Page for wrapped page object - Used by: TemplateEngine for template context - Used in: Templates via template context Baseurl Formats Supported: - Path-only: /bengal → /bengal/docs/page/ - Absolute: https://example.com → https://example.com/docs/page/ - File protocol: file:///path/to/site → file:///path/to/site/docs/page/ - S3: s3://bucket/path → s3://bucket/path/docs/page/ Methods 3 Tag url property URL with baseurl applied (for templates). This is the property templates shoul… str Caret Right def url(self) -> str URL with baseurl applied (for templates). This is the property templates should use for href/src attributes. It automatically includes baseurl, so theme developers don't need to remember to use permalink or filters. Returns str 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). This maintains compatibility with existing templates that use permalink. Returns str Tag relative_url property Relative URL without baseurl (for comparisons). Use this when you need the rel… str Caret Right def relative_url(self) -> str Relative URL without baseurl (for comparisons). Use this when you need the relative URL for comparisons or logic. For display URLs, use .url (which includes baseurl). Returns str Internal Methods 3 Caret Right __init__ Initialize wrapper. 2 None Caret Right def __init__(self, page: Any, baseurl: str = '') Initialize wrapper. Parameters 2 page Any Page object to wrap baseurl str Base URL from site config (can be empty, path-only, or absolute) __getattr__ Delegate all other attributes to wrapped page. This makes the wrapper transpar… 1 Any Caret Right def __getattr__(self, name: str) -> Any Delegate all other attributes to wrapped page. This makes the wrapper transparent - all page properties work as expected. Parameters 1 name str Returns Any __repr__ String representation for debugging. 0 str Caret Right def __repr__(self) -> str String representation for debugging. Returns str TemplateSectionWrapper Wraps Section objects to auto-apply baseurl to .url in templates. Provides transparent wrapper tha… 11 Caret Right Wraps Section objects to auto-apply baseurl to .url in templates. Provides transparent wrapper that automatically applies baseurl to section URLs, similar to TemplatePageWrapper. Also wraps pages and subsections when accessed to ensure consistent baseurl handling throughout the section hierarchy. Creation: Direct instantiation: TemplateSectionWrapper(section, baseurl="") Created by TemplateEngine for template context Requires Section instance and optional baseurl Attributes Name Type Description _section — Wrapped Section object _baseurl — Base URL from site config Relationships — Uses: Section for wrapped section object - Used by: TemplateEngine for template context - Used in: Templates via template context - Wraps: Pages and subsections when accessed Methods 8 Tag url property URL with baseurl applied (for templates). str Caret Right def url(self) -> str URL with baseurl applied (for templates). Returns str Tag permalink property Alias for url (for backward compatibility). str Caret Right def permalink(self) -> str Alias for url (for backward compatibility). Returns str Tag relative_url property Relative URL without baseurl (for comparisons). str Caret Right def relative_url(self) -> str Relative URL without baseurl (for comparisons). Returns str Tag pages property Return wrapped pages. list[TemplatePageWrapper] Caret Right def pages(self) -> list[TemplatePageWrapper] Return wrapped pages. Returns list[TemplatePageWrapper] Tag subsections property Return wrapped subsections. list[TemplateSectio… Caret Right def subsections(self) -> list[TemplateSectionWrapper] Return wrapped subsections. Returns list[TemplateSectionWrapper] Tag sorted_pages property Return wrapped sorted pages. list[TemplatePageWrapper] Caret Right def sorted_pages(self) -> list[TemplatePageWrapper] Return wrapped sorted pages. Returns list[TemplatePageWrapper] Tag sorted_subsections property Return wrapped sorted subsections. list[TemplateSectio… Caret Right def sorted_subsections(self) -> list[TemplateSectionWrapper] Return wrapped sorted subsections. Returns list[TemplateSectionWrapper] Tag index_page property Return wrapped index page. Any Caret Right def index_page(self) -> Any Return wrapped index page. Returns Any Internal Methods 3 Caret Right __init__ Initialize wrapper. 2 None Caret Right def __init__(self, section: Any, baseurl: str = '') Initialize wrapper. Parameters 2 section Any Section object to wrap baseurl str Base URL from site config __getattr__ Delegate all other attributes to wrapped section. 1 Any Caret Right def __getattr__(self, name: str) -> Any Delegate all other attributes to wrapped section. Parameters 1 name str Returns Any __repr__ String representation for debugging. 0 str Caret Right def __repr__(self) -> str String representation for debugging. Returns str TemplateSiteWrapper Wraps Site object to auto-wrap pages/sections when accessed from templates. When templates access … 5 Caret Right Wraps Site object to auto-wrap pages/sections when accessed from templates. When templates access site.pages or site.sections, the pages/sections are automatically wrapped so they have .relative_url and .url includes baseurl. Methods 3 Tag pages property Return wrapped pages. list[TemplatePageWrapper] Caret Right def pages(self) -> list[TemplatePageWrapper] Return wrapped pages. Returns list[TemplatePageWrapper] Tag sections property Return wrapped sections. list[TemplateSectio… Caret Right def sections(self) -> list[TemplateSectionWrapper] Return wrapped sections. Returns list[TemplateSectionWrapper] Tag regular_pages property Return wrapped regular pages. list[TemplatePageWrapper] Caret Right def regular_pages(self) -> list[TemplatePageWrapper] Return wrapped regular pages. Returns list[TemplatePageWrapper] Internal Methods 2 Caret Right __init__ Initialize wrapper. 2 None Caret Right def __init__(self, site: Any, baseurl: str = '') Initialize wrapper. Parameters 2 site Any Site object to wrap baseurl str Base URL from site config __getattr__ Delegate all other attributes to wrapped site. 1 Any Caret Right def __getattr__(self, name: str) -> Any Delegate all other attributes to wrapped site. Parameters 1 name str Returns Any Functions wrap_for_template Wrap Page or Section objects for template context. This function automatically detects the object … 2 Any Caret Right def wrap_for_template(obj: Any, baseurl: str = '') -> Any Wrap Page or Section objects for template context. This function automatically detects the object type and wraps it appropriately. Other objects are returned unchanged. Parameters 2 Name Type Default Description obj Any — Page, Section, SimpleNamespace (special pages), or other object baseurl str '' Base URL from site config Returns Any — Wrapped object (if Page/Section/SimpleNamespace with url) or original object ← Previous rendering Next → template_profiler 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: 2083 - Reading Time: 10 minutes