You use software architecture patterns for that. In that case it could be MVC, which is a subset of 3-tier architecture under the Multilayer architecture
Presentation (UI) should never be in the main logic. You usually have templates/views for that which only has basic control structures like ifs, loops and labels where data is inserted.
Main logic only process the request/input, then gets the data and finally returns you template with a data included.