Search code examples
pythonjinja2python-sphinx

Is there a way to check if a path is absolute in jinja2?


In the pydata-sphinx-theme we need to check if a path is absolute or not before adding it to the template. Currently we use the following:

{% set image_light = image_light if image_light.startswith("http") else pathto('_static/' + image_light, 1) %}

It's working but fails to capture local files and many other absolute configurations. Is there a more elegant way to perform this check ?


Solution

  • thanks @klas Š.for the guidances.

    for anyone coming here I did add:

    from urllib.parse import urlparse
    
    # The registration function
    def setup_is_absolute(app, pagename, templatename, context, doctree):
        def is_absolute(link):
            return bool(urlparse(link).netloc) or link.startswith("/")
        context['is_absolute'] = is_absolute
    
    
     # Your extension's setup function
     def setup(app):
         app.connect("html-page-context", setup_is_absolute)
    

    and in my template:

    {{ is_absolute(logo) }}