The prayer was called, and the rows were straightened with everyone standing. The Messenger of Allah ﷺ came out to us, but when he stood in his place of prayer, he remembered that he was in a state of major ritual impurity, so he said to us, "Stay in your places."He then went back, performed the full bath, and returned to us with water still dripping from his head. He pronounced the opening takbir, and we prayed with him.In another narration, "We had straightened the rows before he came out."
أقيمت الصلاة وعدلت الصفوف قياما، فخرج إلينا رسول الله ﷺ، فلما قام في مصلاه ذكر أنه جنب، فقال لنا: مكانكم. ثم رجع فاغتسل، ثم خرج إلينا ورأسه يقطر، فكبر وصلينا معه. وفي رواية: فعدلنا الصفوف قبل أن يخرج.
Sahih. Bukhari narrated it in ghusl (275) and this is his wording, and Muslim in mosques (605), both of them via Yunus, from Zuhri, from Abu Salama, from Abu Hurairah, who mentioned it. In one version of Muslim, "Before he said the takbir, he remembered, so he left."