"isset或empty中的非法偏移类型"使用Twig宏时 [英] "Illegal offset type in isset or empty" when using a Twig macro
问题描述
使用Grav v1.3.8(在PHP 5.6.30上运行),尝试呈现Twig模板时,当前出现服务器错误("isset中为非法偏移量或为空" )使用宏.
Using Grav v1.3.8 (running on PHP 5.6.30), I'm currently getting a Server error ("Illegal offset type in isset or empty") when trying to render a Twig template that is using a macro.
有趣的是,只有当我自己使用宏时,才会发生这种情况.一旦添加了像trim
这样的过滤器,一切都会按预期进行.
What's interesting is that this only happens when I use the macro by itself. As soon as I append a filter, like trim
, everything works as expected.
(缩短的)宏文件helpers.twig
:
The (shortened) macro file, helpers.twig
:
{% macro ascii(str) %}
{% spaceless %}
{{ str|replace({
'Á': 'A',
'À': 'A',
'Â': 'A',
'Ã': 'A',
....
'ƒ': 'f'
})
}}
{% endspaceless %}
{% endmacro ascii %}
模板(MCVE):
{% import 'macros/helpers.twig' as helpers %}
{% set img = helpers.ascii('günter-berger.jpg') %}
{% if page.media[img] is defined %}
<img src="{{ page.media[img].url }}">
{% endif %}
这将产生错误.我将其范围缩小到if
行.显然,宏可以正常工作,但是如果将条件输出给未过滤的条件,则该条件将引发错误.添加任何过滤器(例如trim
或lower
),将使其重新起作用.
This will produce the error. I narrowed it down to the if
line. Apparently, the macro is working fine, but the condition will throw an error if fed the output of it, unfiltered. Adding any filter, like trim
or lower
, will get it to work again.
换句话说,这些工作:
-
{% if page.media['günter-berger.jpg'] is defined %}
-
{% if page.media[helpers.ascii('günter-berger.jpg')|trim] is defined %}
{% if page.media['günter-berger.jpg'] is defined %}
{% if page.media[helpers.ascii('günter-berger.jpg')|trim] is defined %}
但这会引发错误:
-
{% if page.media[helpers.ascii('günter-berger.jpg')] is defined %}
但是,尝试在twigfiddle上执行相同的操作,这三者似乎都可以正常工作.
也许Grav有问题?有人可以指出任何可能的原因吗?
However, trying the same thing on twigfiddle, all three seem to work there.
Maybe an issue with Grav? Can someone point out any possible causes?
推荐答案
我忘记了这一点,但是宏不返回字符串,而是返回Twig_Markup
I forgot this, but a macro does not return a string but instead returns an instance of a Twig_Markup
{% set test = macro.ascii('Ghünter.jpg') %}
{{ dump(test) }}
输出:object(Twig_Markup)#10679 (2) { ["content":protected]=> string(11) "Ghunter.jpg" ["charset":protected]=> string(5) "UTF-8" }
因为返回类型是一个对象,所以您会收到此通知,因为您不能将对象用作index
.通过在此实例上使用过滤器,将调用magic method
__toString
方法,使其返回字符串,从而使其可用作数组的index
Because the return type is an object you get this notification as you can't use objects as index
. By using a filter on this instance, the magic method
__toString
method will be called, causing it to return a string, thus making it useable as index
for an array
唯一的办法就是绕过这个,那就是写一个filter
而不是一个macro
The only was to bypass this, would be writing a filter
instead of a macro
这篇关于"isset或empty中的非法偏移类型"使用Twig宏时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!