Move DB access out of template