better lists in templates

This commit is contained in:
mProjectsCode 2022-05-13 11:16:22 +02:00
parent 1b31436e58
commit b3ff9d1a38
2 changed files with 60 additions and 9 deletions

View file

@ -13,6 +13,21 @@ Allows you to search by an ID that varies from API to API. Concrete info can be
The plugin allows you to set a template note that gets added to the end of any note created by this plugin.
The plugin also offers simple "template tgs". E.g. if the template includes `{{ title }}`, it will be replaced by the title of the movie, show or game.
Note that "template tags" are surrounded with two curly braces and that the spaces inside the curly braces are important.
For arrays there are two special ways of displaying them.
- using `{{ LIST:variable_name }}` will result in
```
- element 1
- element 2
- element 3
- ...
```
- using `{{ ENUM:variable_name }}` will result in
```
element 1, element 2, element 3, ...
```
I also published my own templates [here](https://github.com/mProjectsCode/obsidian-media-db-templates).
### Currently supported media types

View file

@ -17,29 +17,65 @@ export function replaceIllegalFileNameCharactersInString(string: string) {
}
export function replaceTags(template: string, mediaTypeModel: MediaTypeModel): string {
const resolvedTemplate = template.replace(new RegExp('{{ .*? }}', 'g'), (match: string) => replaceTag(match, mediaTypeModel));
const resolvedTemplate = template.replace(new RegExp('{{.*?}}', 'g'), (match: string) => replaceTag(match, mediaTypeModel));
return resolvedTemplate;
}
function replaceTag(match: string, mediaTypeModel: MediaTypeModel): string {
let tag = match;
tag = tag.substring(3);
tag = tag.substring(0, tag.length - 3);
tag = tag.substring(2);
tag = tag.substring(0, tag.length - 2);
tag = tag.trim();
let parts = tag.split('.');
let parts = tag.split(':');
if (parts.length === 1) {
let path = parts[0].split('.');
let obj = traverseMetaData(path, mediaTypeModel);
if (obj === undefined) {
return '{{ INVALID TEMPLATE TAG }}';
}
return obj;
} else if (parts.length === 2) {
let operator = parts[0];
let path = parts[1].split('.');
let obj = traverseMetaData(path, mediaTypeModel);
if (obj === undefined) {
return '{{ INVALID TEMPLATE TAG }}';
}
if (operator === 'LIST') {
if (!Array.isArray(obj)) {
return '{{ INVALID TEMPLATE TAG - operator LIST is only applicable on an array }}';
}
return obj.map((e: any) => `- ${e}`).join('\n');
} else if (operator === 'ENUM') {
if (!Array.isArray(obj)) {
return '{{ INVALID TEMPLATE TAG - operator ENUM is only applicable on an array }}';
}
return obj.join(', ');
}
return `{{ INVALID TEMPLATE TAG - unknown operator ${operator} }}`;
}
return '{{ INVALID TEMPLATE TAG }}';
}
function traverseMetaData(path: Array<string>, mediaTypeModel: MediaTypeModel): any {
let o: any = mediaTypeModel;
for (let part of parts) {
for (let part of path) {
if (o !== undefined) {
o = o[part];
}
}
if (o === undefined) {
o = '{{ INVALID TEMPLATE TAG }}';
}
return o;
}