Files
directus/app/src/utils/render-string-template.ts
Nitwel ce8401b940 Move some compositons, utils and types to shared (#8059)
* move composables, types and utils to shared

* move composables, utils and types to shared

* expose utils and composables in extensionsSDK

* fix missing dependencies

* Sort index.ts exports

* Do the thing

Co-authored-by: rijkvanzanten <rijkvanzanten@me.com>
2021-09-15 16:41:08 -04:00

49 lines
1.4 KiB
TypeScript

import { render, renderFn, get } from 'micromustache';
import { computed, ComputedRef, Ref, unref } from 'vue';
import { getFieldsFromTemplate } from '@directus/shared/utils';
type StringTemplate = {
fieldsInTemplate: ComputedRef<string[]>;
displayValue: ComputedRef<string | false>;
};
function resolve(path: string, scope: any) {
const value = get(scope, path);
return typeof value === 'object' ? JSON.stringify(value) : value;
}
export function renderStringTemplate(
template: Ref<string | null> | string,
item: Record<string, any> | undefined | null | Ref<Record<string, any> | undefined | null>
): StringTemplate {
const values = unref(item);
const templateString = unref(template);
const fieldsInTemplate = computed(() => getFieldsFromTemplate(templateString));
const displayValue = computed(() => {
if (!values || !templateString || !fieldsInTemplate.value) return false;
try {
return renderFn(templateString, resolve, values, { propsExist: true });
} catch {
return false;
}
});
return { fieldsInTemplate, displayValue };
}
export function renderPlainStringTemplate(template: string, item?: Record<string, any> | null): string | null {
const fieldsInTemplate = getFieldsFromTemplate(template);
if (!item || !template || !fieldsInTemplate) return null;
try {
return render(template, item, { propsExist: true });
} catch {
return null;
}
}