v2 / vlib / x / templating / dtm / dynamic_template_manager_dtm2_bridge.v
65 lines · 59 sloc · 2.36 KB · 3eff1b83cf719199d0ff6f63524da63c9294ffd5
Raw
1module dtm
2
3import x.templating.dtm2
4
5// new_dtm2_render_engine is the compatibility boundary between the historical
6// DTM API and the DTM2 runtime template engine. DTM2 remains unaware
7// of legacy cache concepts; it only parses templates and renders them.
8fn new_dtm2_render_engine(template_dir string, compress_html bool) &dtm2.Manager {
9 return dtm2.initialize(
10 template_dir: template_dir
11 compress_html: compress_html
12 reload_modified_templates: true
13 )
14}
15
16fn (mut tm DynamicTemplateManager) expand_with_dtm2_render_engine(tmpl_path string, tmpl_var TemplateCacheParams) string {
17 validate_legacy_placeholder_sizes(tmpl_path, tmpl_var.placeholders) or {
18 eprintln(err.msg())
19 return internat_server_error
20 }
21 if isnil(tm.render_engine) {
22 tm.render_engine = new_dtm2_render_engine(tm.template_folder, tm.compress_html)
23 }
24 placeholders := convert_legacy_placeholders(tmpl_var.placeholders)
25 return tm.render_engine.expand(tmpl_path,
26 placeholders: &placeholders
27 missing_placeholder_prefix: '$'
28 )
29}
30
31fn validate_legacy_placeholder_sizes(tmpl_path string, placeholders &map[string]DtmMultiTypeMap) ! {
32 for key, value in placeholders {
33 if key.len > max_placeholders_key_size {
34 return error('${message_signature_error} Length of placeholder key "${key}" exceeds the maximum allowed size for template content in file: ${tmpl_path}. Max allowed size: ${max_placeholders_key_size} characters.')
35 }
36 casted_value := legacy_placeholder_value_to_string(*value)
37 if casted_value.len > max_placeholders_value_size {
38 return error('${message_signature_error} Length of placeholder value for key "${key}" exceeds the maximum allowed size for template content in file: ${tmpl_path}. Max allowed size: ${max_placeholders_value_size} characters.')
39 }
40 }
41}
42
43fn convert_legacy_placeholders(placeholders &map[string]DtmMultiTypeMap) map[string]string {
44 mut converted := map[string]string{}
45 for key, value in placeholders {
46 converted[key.clone()] = legacy_placeholder_value_to_string(*value).clone()
47 }
48 return converted
49}
50
51fn legacy_placeholder_value_to_string(value DtmMultiTypeMap) string {
52 return match value {
53 f32 { value.str() }
54 f64 { value.str() }
55 i16 { value.str() }
56 i64 { value.str() }
57 i8 { value.str() }
58 int { value.str() }
59 string { value.clone() }
60 u16 { value.str() }
61 u32 { value.str() }
62 u64 { value.str() }
63 u8 { value.str() }
64 }
65}
66