Skip to content

Commit

Permalink
fix: handlebars template exec function calling with kcl json value (#…
Browse files Browse the repository at this point in the history
…1457)

Signed-off-by: peefy <[email protected]>
  • Loading branch information
Peefy authored Jun 29, 2024
1 parent 3f2e611 commit 4907018
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 3 deletions.
4 changes: 2 additions & 2 deletions kclvm/runtime/src/template/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ pub extern "C" fn kclvm_template_execute(
.register_template_string("template", template)
.expect("register template failed");
let data = get_call_arg(args, kwargs, 1, Some("data")).unwrap_or(ValueRef::dict(None));
let data: HashMap<String, String> = HashMap::from_iter(
let data: HashMap<String, JsonValue> = HashMap::from_iter(
data.as_dict_ref()
.values
.iter()
.map(|(k, v)| (k.to_string(), v.to_string())),
.map(|(k, v)| (k.to_string(), v.build_json(&Default::default()))),
);
let result = handlebars
.render("template", &data)
Expand Down
2 changes: 1 addition & 1 deletion kclvm/runtime/src/value/val_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ impl ValueRef {
writer.to_str().unwrap().to_string()
}

fn build_json(&self, opt: &JsonEncodeOptions) -> JsonValue {
pub(crate) fn build_json(&self, opt: &JsonEncodeOptions) -> JsonValue {
match &*self.rc.borrow() {
crate::Value::undefined => JsonValue::Null,
crate::Value::none => JsonValue::Null,
Expand Down
32 changes: 32 additions & 0 deletions test/grammar/builtins/template/execute_2/main.k
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import template

_data = {
name = "handlebars",
v = [ { a = 1}, { a = 2}],
c = { d = 5},
g = { b = [{ aa = { bb = 55}}, { aa = { bb = 66} } ] },
people = [ "Yehuda Katz", "Alan Johnson", "Charles Jolley" ]
}

content = template.execute("""\
Hello world from {{name}}

{{#each v}}
{{this.a}}
{{/each}}
{{ c.d }}
{{#each people}}
{{ this }}
{{/each}}
{{#each g.b}}
{{this.aa.bb}}
{{/each}}
""", _data)

content_raw = template.execute("""\
{{this.name}}
{{this.v}}
{{this.c}}
{{this.g}}
{{this.people}}
""", _data)
17 changes: 17 additions & 0 deletions test/grammar/builtins/template/execute_2/stdout.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
content: |
Hello world from handlebars

1
2
5
Yehuda Katz
Alan Johnson
Charles Jolley
55
66
content_raw: |
handlebars
[[object], [object]]
[object]
[object]
[Yehuda Katz, Alan Johnson, Charles Jolley]

0 comments on commit 4907018

Please sign in to comment.