php-liquid
php-liquid copied to clipboard
Can't use variables as index in array
With the original Liquid implementation, you are able to set an integer as a variable, and then use it inside bracket notation of an array/object to output the value of that key. This doesn't work in the PHP version:
Example:
{% assign letters = 'A,B,C,D,E' | split: ',' %}
{{ letters[1] }}
B
{% assign index = 1 %}
{{ letters[index] }}
blank
I've fixed this by modifying the "variable" method in the LiquidContext class:
/**
* Resolved the namespaced queries gracefully.
*
* @param string $key
* @return mixed
*/
public function variable($key)
{
/* Support [0] style array indicies */
if (preg_match("|\[[0-9]+\]|", $key))
{
$key = preg_replace("|\[([0-9]+)\]|", ".$1", $key);
}
/* Support [var] style array indicies */
elseif (preg_match("|\[(.*)\]|", $key, $matches))
{
$var = $this->fetch($matches[1]);
$key = preg_replace("|\[(.*)\]|", "." . $var, $key);
}
.....