MCPcopy Index your code
hub / github.com/GitbookIO/gitbook / parseTemplate

Function parseTemplate

packages/expr/src/template.ts:20–57  ·  view source on GitHub ↗
(template: string)

Source from the content-addressed store, hash-verified

18 * Parse a template string containing `{{ expression }}` placeholders.
19 */
20export function parseTemplate(template: string): TemplatePart[] {
21 const parts: TemplatePart[] = [];
22 const regex = /\{\{(.*?)\}\}/gs;
23 let lastIndex = 0;
24
25 for (const match of template.matchAll(regex)) {
26 const matchStart = match.index ?? 0;
27 const matchEnd = matchStart + match[0].length;
28
29 if (matchStart > lastIndex) {
30 parts.push({
31 type: 'text',
32 value: template.slice(lastIndex, matchStart),
33 start: lastIndex,
34 end: matchStart,
35 });
36 }
37
38 parts.push({
39 type: 'expression',
40 value: (match[1] ?? '').trim(),
41 start: matchStart + 2,
42 end: matchEnd - 2,
43 });
44 lastIndex = matchEnd;
45 }
46
47 if (lastIndex < template.length) {
48 parts.push({
49 type: 'text',
50 value: template.slice(lastIndex),
51 start: lastIndex,
52 end: template.length,
53 });
54 }
55
56 return parts;
57}

Calls

no outgoing calls

Tested by

no test coverage detected