Import on complex deep object
See original GitHub issueFirst of all, thanks for the wonderful library! Seems to be exactly what I need!
I’ve tried to make it work for my case, but I’m unable to get it working. I hope you can point me into the right direction.
First try (basic sample)
Data:
var data = new
{
floors = new []
{
new
{
name = "foo",
walls = new []
{
new { x = 1, y = 1 }
}
},
new
{
name = "bar",
walls = new []
{
new { x = 2, y = 2 }
}
}
}
};
Template:
<stack>
{{ for floor in floors }}
{{ floor.name }}
{{ for wall in floor.walls }}
{{ wall.x }}, {{ wall.y }}
{{ end }}
{{ end }}
</stack>
Code:
var scriptObject = new ScriptObject();
scriptObject.Add("floors", data.floors);
var context = new TemplateContext();
context.PushGlobal(scriptObject);
var template = Template.Parse(text);
var result = template.Render(context);
return result;
This resulted in:
<stack>
foo
1, 1
bar
2, 2
</stack>
So this works!
Second try (add sub templates)
The template would become huge if I could not split it in smaller ones. So, now using sub templates.
Code:
I’ve added a template loader so that I can resolve templates to be included.
context.TemplateLoader = templateLoader;
Template house (like first try template):
<stack>
{{ for floor in floors }}
{{ include 'floor' }}
{{ end }}
</stack>
Template ‘floor’:
<g>
{{ floor.name }}
</g>
Result:
<stack>
<g>
foo
</g>
<g>
bar
</g>
</stack>
So this also works!
Third try (add import)
I don’t really want to use floor
as a variable in the sub-template. This template should not know about the variable the parent template has used. So, I tried using import floor
.
Template house:
<stack>
{{ for floor in floors }}
{{
import floor
include 'floor'
}}
{{ end }}
</stack>
Template floor:
<g>
{{ name }}
</g>
Result:
Scriban.Syntax.ScriptRuntimeException: 'Unexpected value `<>f__AnonymousType1`2[System.String,<>f__AnonymousType2`2[System.Int32,System.Int32][]]` for import. Expecting an plain script object {}'
Question
How to resolve this error?
I’ve tried to do it via JObject (via JSON) but I get a similar error:
Scriban.Syntax.ScriptRuntimeException: 'Unexpected value `Newtonsoft.Json.Linq.JObject` for import. Expecting an plain script object {}'
I’ve also tried to do it via ExpandoObject, but still a similar error:
Scriban.Syntax.ScriptRuntimeException: 'Unexpected value `System.Dynamic.ExpandoObject` for import. Expecting an plain script object {}'
Issue Analytics
- State:
- Created 5 years ago
- Comments:10 (1 by maintainers)
Top GitHub Comments
It worked! This is an elegant solution to a very frequent problem that I have. Thanks a lot, @promontis!
@leosdad sorry… copy/paste went wrong 😃 I’ve updated the code! Good luck 🤗