Resolve template path inside of DCC

I need to resolve template path inside tk-maya to give direct path to artists who need them.

I have a solution using tk.templates, but it seems pretty complicated and I want to be sure there is no simpler way to do that:

:diamonds: Is there any way to get my template key name from the current context?
If I’m inside tk-maya working on an Asset on a work scene, doesn’t SGTK already know which key to call? (eg ‘maya_shot_work’)

:diamonds: From tk-core help, there is this exemple:

get a template object from the API

template_obj = sgtk.templates[“maya_shot_work”]
<Sgtk Template maya_asset_project: shots/{Shot}/{Step}/pub/{name}.v{version}.ma>

fields = {‘Shot’: ‘001_002’,
‘Step’: ‘comp’,
‘name’: ‘main_scene’,
‘version’: 3


This handy method even gives us all missing_keys from the template object:

For exemple, to get ‘maya_shot_work’ from inside a Maya Shot scene, I would need:

'Shot' -> Is this the entity type?
'name' -> engine.context.entity[‘name’]
'extension' -> cmds.file(q=1, sn=1).split(’.’)[-1]
'project_initials' -> query through API
'version' -> os.path.splitext(cmds.file(q=1, sn=1).split(’_’)[-1])[0]
'task_name' -> engine.context.task[‘name’]
'Episode' -> query through API

The thing is, I need to pull informations from a lot of different templates keys. I’m gonna need to
copy every key used in template.yml to tell my module how to translate them.

More problematic: if I need to add new keys or modify existing template paths in template.yml, I will probably need to redo this whole script.

Is there a quicker / simpler way to query all those informations? How does SGTK get all those the same way when creating new paths, or is there a secret class hidden somewhere?

Thanks a lot!

1 Like

Philip helped me out:

tk = sgtk.Sgtk(currentScenePath)
currentTemplate = tk.templates["maya_shot_work"]
ctx = engine.context
fieldsResolved = ctx.as_template_fields(currentTemplate)

This returns a dictionnary with keys needed in the desired template:

template = {Episode}/{Shot}/{task_name}/scenes/work/{project_initials}_{Shot}_{task_name}_{name}_v{version}.{extension}

{'Episode': 'ep101', 'Shot': 'ep101_sh0010', 'project_initials': 'sb', 'task_name': 'animation'}

Note that it does not return scene scpecific keys such as name, version and extension, but those are pretty easily queried through your scene path.

ctx.as_template_fields will return an error if fields are not all complete, so make sure you got everything from missing_keys() before applying fields.

Thanks a lot Philip!