如何从Grav CMS的树枝模板中的URL中修剪协议
问题描述:
我需要从使用Grav CMS的树枝模板输出没有协议(http:或https :)的URL。如何从Grav CMS的树枝模板中的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()) }}" />
我得到一个空字符串,当我把这个宏。
答
我发现Grav CMS提供了一个regex_replace函数。
这里是我的解决方案: <meta property="og:url" content="{{ page.url()|regex_replace('/^https?:/', '') }}" />