Refactor template filtering