refactor: removing a few unnecessary loops and moving HTML out of script into template