Refactor templating mechanism

No, because `doc.document_type.templates[name]` or `overrided[id].templates[name]` could still be `undefined`.