Many posts in the forum explain this.
Here’s a simple snippet: Can someone create a "split and title" script
So why not make the script inside the template package do all of this for you? You’re already doing the heavy lifting of inventing a script to follow your logic rules. A script’s a script. Bundle it with your doc template, use DEVONthink’s text substitutions if needed (or customize your own) and you have a package that might be more functional. Look inside any of the .templatescriptd packages in ~/Library/DEVONthink Pro 2/Scripts.
The forum is full of custom template examples.