The goal is to be able to modify values of variables used in templates. It enables future functionality such as escaping, inlining etc. It adds support applying predefined pipes to variables. Pipes can be applied to variable substitution in with and parameter substitution expressions. They work in similar way to piping in Unix where each pipe applied to the compiled result of pipe before. It adds support for using pipes in `with` and parameter substitution expressions. It also refactors how their regex is build to reuse more of the logic by abstracting regex building into a new class. Finally, it separates and extends documentation for templating.
59 lines
2.3 KiB
TypeScript
59 lines
2.3 KiB
TypeScript
import { RegexParser, IPrimitiveExpression } from '../Parser/Regex/RegexParser';
|
|
import { FunctionParameter } from '@/application/Parser/Script/Compiler/Function/Parameter/FunctionParameter';
|
|
import { ExpressionRegexBuilder } from '../Parser/Regex/ExpressionRegexBuilder';
|
|
|
|
export class WithParser extends RegexParser {
|
|
protected readonly regex = new ExpressionRegexBuilder()
|
|
// {{ with $parameterName }}
|
|
.expectExpressionStart()
|
|
.expectCharacters('with')
|
|
.expectOneOrMoreWhitespaces()
|
|
.expectCharacters('$')
|
|
.matchUntilFirstWhitespace() // First match: parameter name
|
|
.expectExpressionEnd()
|
|
// ...
|
|
.matchAnythingExceptSurroundingWhitespaces() // Second match: Scope text
|
|
// {{ end }}
|
|
.expectExpressionStart()
|
|
.expectCharacters('end')
|
|
.expectExpressionEnd()
|
|
.buildRegExp();
|
|
|
|
protected buildExpression(match: RegExpMatchArray): IPrimitiveExpression {
|
|
const parameterName = match[1];
|
|
const scopeText = match[2];
|
|
return {
|
|
parameters: [ new FunctionParameter(parameterName, true) ],
|
|
evaluator: (context) => {
|
|
const argumentValue = context.args.hasArgument(parameterName) ?
|
|
context.args.getArgument(parameterName).argumentValue
|
|
: undefined;
|
|
if (!argumentValue) {
|
|
return '';
|
|
}
|
|
return replaceEachScopeSubstitution(scopeText, (pipeline) => {
|
|
if (!pipeline) {
|
|
return argumentValue;
|
|
}
|
|
return context.pipelineCompiler.compile(argumentValue, pipeline);
|
|
});
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
const ScopeSubstitutionRegEx = new ExpressionRegexBuilder()
|
|
// {{ . | pipeName }}
|
|
.expectExpressionStart()
|
|
.expectCharacters('.')
|
|
.matchPipeline() // First match: pipeline
|
|
.expectExpressionEnd()
|
|
.buildRegExp();
|
|
|
|
function replaceEachScopeSubstitution(scopeText: string, replacer: (pipeline: string) => string) {
|
|
// Not using /{{\s*.\s*(?:(\|\s*[^{}]*?)\s*)?}}/g for not matching brackets, but let pipeline compiler fail on those
|
|
return scopeText.replaceAll(ScopeSubstitutionRegEx, (_$, match1 ) => {
|
|
return replacer(match1);
|
|
});
|
|
}
|