1 |
|
2 |
|
3 | const compile = require('lodash.template')
|
4 | const compileOptions = {
|
5 | escape: /{{([^{][\s\S]+?[^}])}}/g,
|
6 | interpolate: /{{{([\s\S]+?)}}}/g
|
7 | }
|
8 |
|
9 | export type ParsedTemplate = {
|
10 | head: (data: any) => string;
|
11 | neck: (data: any) => string;
|
12 | tail: (data: any) => string;
|
13 | };
|
14 |
|
15 | export function parseTemplate (
|
16 | template: string,
|
17 | contentPlaceholder?: string = '<!--vue-ssr-outlet-->'
|
18 | ): ParsedTemplate {
|
19 | if (typeof template === 'object') {
|
20 | return template
|
21 | }
|
22 |
|
23 | let i = template.indexOf('</head>')
|
24 | const j = template.indexOf(contentPlaceholder)
|
25 |
|
26 | if (j < 0) {
|
27 | throw new Error(`Content placeholder not found in template.`)
|
28 | }
|
29 |
|
30 | if (i < 0) {
|
31 | i = template.indexOf('<body>')
|
32 | if (i < 0) {
|
33 | i = j
|
34 | }
|
35 | }
|
36 |
|
37 | return {
|
38 | head: compile(template.slice(0, i), compileOptions),
|
39 | neck: compile(template.slice(i, j), compileOptions),
|
40 | tail: compile(template.slice(j + contentPlaceholder.length), compileOptions)
|
41 | }
|
42 | }
|