0

I'm needing to output a URL without the protocol (http: or https:) from a twig template usin Grav CMS.

What is the best way to do this?

Twig provides a MATCH function for comparisons that uses regex, and a REPLACE function that does not use regex.

Therefore, it seems I am stuck with doing a convoluted if statement such as:

`

    {% if url starts with 'https:' %}   
        {{ url|replace('https:') }}
    {% else %}

        {% if url starts with 'http:' %}
            {{ url|replace('http:') }}
        {% else %}
            {{ url }}
        {% endif %}

`

Is there a better way of doing this feat? If I put this code in a macro, how can I utilize the macro? Here is the complete macro:

`

{% macro fixUrl(url) %}
    {% if url %}
        {% if url starts with 'https:' %}   
            {{ url|replace('https:') }}
        {% else %}

            {% if url starts with 'http:' %}
                {{ url|replace('http:') }}
            {% else %}
                {{ url }}
            {% endif %}
        {% endif %}
    {% endif %}

{% endmacro %}

`

And I call macro like: <meta property="og:url" content="{{ self.fixUrl(page.url()) }}" />

I'm getting an empty string when I call this macro.

Jeff Wilkerson
  • 376
  • 2
  • 18

1 Answers1

1

I've discovered that Grav CMS provides a regex_replace function.

Here is my solution: <meta property="og:url" content="{{ page.url()|regex_replace('/^https?:/', '') }}" />

Jeff Wilkerson
  • 376
  • 2
  • 18