1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//! Minimal mustache template engine.
//!
//! Supports basic variable interpolation (`{{var}}`), sections (`{{#section}}`),
//! inverted sections (`{{^section}}`), and HTML escaping.
//!
//! Inspired by Python `langchain_core.utils.mustache` (from chevron).
use serde_json::Value;
use crate::error::{CognisError, Result};
/// Render a mustache template with the given data.
pub fn render(template: &str, data: &Value) -> Result<String> {
let scopes = vec![data.clone()];
render_with_scopes(template, &scopes)
}
fn render_with_scopes(template: &str, scopes: &[Value]) -> Result<String> {
let mut output = String::new();
let mut remaining = template;
while !remaining.is_empty() {
// Find the next tag
if let Some(tag_start) = remaining.find("{{") {
// Add literal text before the tag
output.push_str(&remaining[..tag_start]);
let after_open = &remaining[tag_start + 2..];
if let Some(tag_end) = after_open.find("}}") {
let tag_content = after_open[..tag_end].trim();
remaining = &after_open[tag_end + 2..];
if tag_content.is_empty() {
continue;
}
let first_char = tag_content.chars().next().unwrap();
match first_char {
// Comment: {{! ... }}
'!' => {
// Skip comment
}
// Unescaped: {{{ var }}} or {{& var }}
'&' => {
let key = tag_content[1..].trim();
let val = get_key(key, scopes);
output.push_str(&value_to_string(&val));
}
'{' => {
// Triple mustache: {{{ var }}}
let key = tag_content[1..].trim();
// Need to consume the extra closing brace
if remaining.starts_with('}') {
remaining = &remaining[1..];
}
let val = get_key(key, scopes);
output.push_str(&value_to_string(&val));
}
// Section: {{# section }}...{{/ section }}
'#' => {
let section_name = tag_content[1..].trim();
let (section_body, rest) = find_section_end(remaining, section_name)?;
remaining = rest;
let val = get_key(section_name, scopes);
match &val {
Value::Bool(false) | Value::Null => {
// Falsy: skip section
}
Value::Array(arr) => {
for item in arr {
let mut new_scopes = scopes.to_vec();
new_scopes.push(item.clone());
output
.push_str(&render_with_scopes(section_body, &new_scopes)?);
}
}
Value::Object(_) => {
let mut new_scopes = scopes.to_vec();
new_scopes.push(val.clone());
output.push_str(&render_with_scopes(section_body, &new_scopes)?);
}
_ => {
// Truthy: render once
output.push_str(&render_with_scopes(section_body, scopes)?);
}
}
}
// Inverted section: {{^ section }}...{{/ section }}
'^' => {
let section_name = tag_content[1..].trim();
let (section_body, rest) = find_section_end(remaining, section_name)?;
remaining = rest;
let val = get_key(section_name, scopes);
let is_falsy = match &val {
Value::Bool(false) | Value::Null => true,
Value::Array(arr) => arr.is_empty(),
_ => false,
};
if is_falsy {
output.push_str(&render_with_scopes(section_body, scopes)?);
}
}
// Partial: {{> partial }} — not supported, skip
'>' => {}
// Variable
_ => {
let val = get_key(tag_content, scopes);
output.push_str(&html_escape(&value_to_string(&val)));
}
}
} else {
// No closing }}, add rest as literal
output.push_str(&remaining[tag_start..]);
break;
}
} else {
// No more tags, add remaining literal text
output.push_str(remaining);
break;
}
}
Ok(output)
}
/// Find the end of a section, handling nested sections.
fn find_section_end<'a>(template: &'a str, name: &str) -> Result<(&'a str, &'a str)> {
let open_tag = format!("{{{{#{}}}}}", name);
let close_tag = format!("{{{{/{}}}}}", name);
let mut depth = 1;
let mut search = template;
let mut body_end = 0;
while depth > 0 {
let next_open = search.find(&open_tag);
let next_close = search.find(&close_tag);
match (next_open, next_close) {
(_, Some(close_pos)) => {
let open_before_close = next_open.is_some_and(|op| op < close_pos);
if open_before_close {
let op = next_open.unwrap();
depth += 1;
let advance = op + open_tag.len();
body_end += advance;
search = &search[advance..];
} else {
depth -= 1;
if depth == 0 {
let body = &template[..body_end + close_pos];
let rest = &search[close_pos + close_tag.len()..];
return Ok((body, rest));
}
let advance = close_pos + close_tag.len();
body_end += advance;
search = &search[advance..];
}
}
(_, None) => {
return Err(CognisError::Other(format!(
"Unclosed mustache section: {}",
name
)));
}
}
}
unreachable!()
}
/// Look up a dot-separated key in the scope stack.
fn get_key(key: &str, scopes: &[Value]) -> Value {
if key == "." {
return scopes.last().cloned().unwrap_or(Value::Null);
}
let parts: Vec<&str> = key.split('.').collect();
// Search scopes from innermost to outermost.
for scope in scopes.iter().rev() {
let mut current = scope;
let mut found = true;
for part in &parts {
match current {
Value::Object(map) => {
if let Some(val) = map.get(*part) {
current = val;
} else {
found = false;
break;
}
}
_ => {
found = false;
break;
}
}
}
if found {
return current.clone();
}
}
Value::Null
}
fn value_to_string(val: &Value) -> String {
match val {
Value::String(s) => s.clone(),
Value::Null => String::new(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
other => other.to_string(),
}
}
fn html_escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
/// Extract top-level variable names from a mustache template.
pub fn template_vars(template: &str) -> Vec<String> {
let mut vars = Vec::new();
let mut remaining = template;
while let Some(pos) = remaining.find("{{") {
let after = &remaining[pos + 2..];
if let Some(end) = after.find("}}") {
let tag = after[..end].trim();
if !tag.is_empty() {
let first = tag.chars().next().unwrap();
let var_name = match first {
'#' | '^' | '/' | '!' | '>' | '&' => tag[1..].trim().to_string(),
'{' => tag[1..].trim().to_string(),
_ => tag.to_string(),
};
// Only add top-level (no dots), skip section ends and comments
if first != '/' && first != '!' && !var_name.is_empty() && !vars.contains(&var_name)
{
vars.push(var_name);
}
}
remaining = &after[end + 2..];
} else {
break;
}
}
vars
}