--- /dev/null
+``first``
+=========
+
+.. versionadded:: 1.12.2
+ The first filter was added in Twig 1.12.2.
+
+The ``first`` filter returns the first "element" of a sequence, a mapping, or
+a string:
+
+.. code-block:: jinja
+
+ {{ [1, 2, 3, 4]|first }}
+ {# outputs 1 #}
+
+ {{ { a: 1, b: 2, c: 3, d: 4 }|first }}
+ {# outputs 1 #}
+
+ {{ '1234'|first }}
+ {# outputs 1 #}
+
+.. note::
+
+ It also works with objects implementing the `Traversable`_ interface.
+
+.. _`Traversable`: http://php.net/manual/en/class.traversable.php
--- /dev/null
+``last``
+========
+
+.. versionadded:: 1.12.2
+ The last filter was added in Twig 1.12.2.
+
+The ``last`` filter returns the last "element" of a sequence, a mapping, or
+a string:
+
+.. code-block:: jinja
+
+ {{ [1, 2, 3, 4]|last }}
+ {# outputs 4 #}
+
+ {{ { a: 1, b: 2, c: 3, d: 4 }|last }}
+ {# outputs 4 #}
+
+ {{ '1234'|last }}
+ {# outputs 4 #}
+
+.. note::
+
+ It also works with objects implementing the `Traversable`_ interface.
+
+.. _`Traversable`: http://php.net/manual/en/class.traversable.php
new Twig_SimpleFilter('reverse', 'twig_reverse_filter', array('needs_environment' => true)),
new Twig_SimpleFilter('length', 'twig_length_filter', array('needs_environment' => true)),
new Twig_SimpleFilter('slice', 'twig_slice', array('needs_environment' => true)),
+ new Twig_SimpleFilter('first', 'twig_first', array('needs_environment' => true)),
+ new Twig_SimpleFilter('last', 'twig_last', array('needs_environment' => true)),
// iteration and runtime
new Twig_SimpleFilter('default', '_twig_default_filter', array('node_class' => 'Twig_Node_Expression_Filter_Default')),
}
/**
+ * Returns the first element of the item.
+ *
+ * @param Twig_Environment $env A Twig_Environment instance
+ * @param mixed $item A variable
+ *
+ * @return mixed The first element of the item
+ */
+function twig_first(Twig_Environment $env, $item)
+{
+ $elements = twig_slice($env, $item, 0, 1, false);
+
+ return is_string($elements) ? $elements[0] : current($elements);
+}
+
+/**
+ * Returns the last element of the item.
+ *
+ * @param Twig_Environment $env A Twig_Environment instance
+ * @param mixed $item A variable
+ *
+ * @return mixed The last element of the item
+ */
+function twig_last(Twig_Environment $env, $item)
+{
+ $elements = twig_slice($env, $item, -1, 1, false);
+
+ return is_string($elements) ? $elements[0] : current($elements);
+}
+
+/**
* Joins the values to a string.
*
* The separator between elements is an empty string per default, you can define it with the optional parameter.
--- /dev/null
+--TEST--
+"first" filter
+--TEMPLATE--
+{{ [1, 2, 3, 4]|first }}
+{{ {a: 1, b: 2, c: 3, d: 4}|first }}
+{{ '1234'|first }}
+{{ arr|first }}
+--DATA--
+return array('arr' => new ArrayObject(array(1, 2, 3, 4)))
+--EXPECT--
+1
+1
+1
+1