如何从Grav CMS的Twig模板中的URL修剪协议

时间:2017-06-22 17:42:17

标签: twig grav

我需要在Grav CMS中使用twig模板输出没有协议的URL(http:或https :)。

这样做的最佳方式是什么?

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()) }}" />

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

1 个答案:

答案 0 :(得分:1)

我发现Grav CMS提供regex_replace功能。

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

相关问题