mirror of
https://github.com/portainer/portainer.git
synced 2025-08-04 13:25:26 +02:00
refactor(custom-templates): render template variables [EE-2602] (#6937)
This commit is contained in:
parent
71c0e8e661
commit
1ccdb64938
32 changed files with 829 additions and 47 deletions
72
app/react/portainer/custom-templates/components/utils.ts
Normal file
72
app/react/portainer/custom-templates/components/utils.ts
Normal file
|
@ -0,0 +1,72 @@
|
|||
import _ from 'lodash';
|
||||
import Mustache from 'mustache';
|
||||
|
||||
import { VariableDefinition } from './CustomTemplatesVariablesDefinitionField/CustomTemplatesVariablesDefinitionField';
|
||||
|
||||
export function getTemplateVariables(templateStr: string) {
|
||||
const template = validateAndParse(templateStr);
|
||||
|
||||
if (!template) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return template
|
||||
.filter(([type, value]) => type === 'name' && value)
|
||||
.map(([, value]) => ({
|
||||
name: value,
|
||||
label: '',
|
||||
defaultValue: '',
|
||||
description: '',
|
||||
}));
|
||||
}
|
||||
|
||||
function validateAndParse(templateStr: string) {
|
||||
if (!templateStr) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
return Mustache.parse(templateStr);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function intersectVariables(
|
||||
oldVariables: VariableDefinition[] = [],
|
||||
newVariables: VariableDefinition[] = []
|
||||
) {
|
||||
const oldVariablesWithLabel = oldVariables.filter((v) => !!v.label);
|
||||
|
||||
return [
|
||||
...oldVariablesWithLabel,
|
||||
...newVariables.filter(
|
||||
(v) => !oldVariablesWithLabel.find(({ name }) => name === v.name)
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
export function renderTemplate(
|
||||
template: string,
|
||||
variables: Record<string, string>,
|
||||
definitions: VariableDefinition[]
|
||||
) {
|
||||
const state = Object.fromEntries(
|
||||
_.compact(
|
||||
Object.entries(variables).map(([name, value]) => {
|
||||
if (value) {
|
||||
return [name, value];
|
||||
}
|
||||
|
||||
const definition = definitions.find((def) => def.name === name);
|
||||
if (!definition) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [name, definition.defaultValue || `{{ ${definition.name} }}`];
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
return Mustache.render(template, state);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue