Search code examples
jekyllliquidgithub-pages

How to know if an URL is relative or absolute in Jekyll?


I'm trying to do the following in Jekyll:

Sadly I have no clue yet on how to achieve this.

I'd love if somebody could help me.

Thanks in advance.


Solution

  • You can do this using liquid. Here is a basic example of what you could do. You will probably want to adjust it for your own use.

    {% assign myurl = "/css/bootstrap.min.css" %}
    {% if myurl contains '://' %}
    {{myurl}}
    {% else %}
    {{ myurl | prepend: site.url }}
    {% endif %}
    

    Breaking down the code:

    This line just creates a variable holding the url:

    {% assign myurl = "/css/bootstrap.min.css" %}
    

    Next, we will check if the url is absolute. This simple version does that by checking the string, ://, is in the url:

    {% if myurl contains '://' %}
    

    If the url does, liquid will simply print out the url variable:

    {{myurl}}
    

    If not, liquid will prepend the site's url to the beginning of url and print the complete url:

    {% else %}
    {{ myurl | prepend: site.url }}
    {% endif %}