【发布时间】: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()) }}" />
当我调用这个宏时得到一个空字符串。
【问题讨论】: