You don't need to mix logic with templates. I just produce a context (result from database queries and some such) and pass it to a function that produces HTML from the data in the context. The data must not be changed in the templating function. This is something I try to avoid as well in order to maintain separation of concerns in the backend code.
Edit for clarification: The context holds the data that is rendered as-is by the templating function. So any transformations from the "raw" database data and the context data happens beforehand and the templating function just turns it into HTML.
Edit for clarification: The context holds the data that is rendered as-is by the templating function. So any transformations from the "raw" database data and the context data happens beforehand and the templating function just turns it into HTML.