harrydeluxe / php-liquid

A PHP port of Ruby's Liquid Templates
http://www.delacap.com/artikel/Liquid-Templates/
MIT License
239 stars 119 forks source link

Can't use variables as index in array #31

Open schmoove opened 8 years ago

schmoove commented 8 years ago

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);
        }
       .....