Moved looping of elements into template (should be faster)