I rather prefer to have $templatedir within template instead of doing chdir in a code. The chdir is not thread safe, whlle $templatedir will not fine in threaded environment. Please convert template to use $templatedir and pass it into template.