Then define it so other templates can use it too? With proper doc block and unit tests?

Even a function in this template file seems better than repeating code. You could use an anonymous function in order to not pollute global space. See http://php.net/manual/en/functions.anonymous.php