【问题标题】:How to trim the protocol from a URL in a Twig Template for Grav CMS如何从 Grav CMS 的 Twig 模板中的 URL 修剪协议
【发布时间】:2026-01-25 22:05:02
【问题描述】:

我需要使用 Grav CMS 从树枝模板中输出不带协议(http: 或 https:) 的 URL。

最好的方法是什么?

Twig 提供了一个使用正则表达式的 MATCH function for comparisons 和一个不使用正则表达式的 REPLACE function

因此,我似乎坚持做一个复杂的 if 语句,例如:

`

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

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

`

有没有更好的方法来完成这个壮举?如果我把这段代码放在一个宏中,我该如何利用这个宏?这是完整的宏:

`

{% 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 %}

`

我将宏称为:<meta property="og:url" content="{{ self.fixUrl(page.url()) }}" />

当我调用这个宏时得到一个空字符串。

【问题讨论】:

    标签: twig grav


    【解决方案1】:

    我发现 Grav CMS 提供了regex_replace 函数。

    这是我的解决方案: <meta property="og:url" content="{{ page.url()|regex_replace('/^https?:/', '') }}" />

    【讨论】: