This is my jinja template to generate C# code from my data model
using System;
namespace {{ domain["ns"] }} {
{% for class in domain["content"] %}
public class {{ class["name"] }} {
#region Inners
{{ class["innerClass"] }}
#endregion
#region Props
{% for field in class["content"] %}
{% if field["readonly"] == "true" %}
{% set readonly="private" %}
{% else %}
{% set readonly="" %}
{% endif %}
public {{ field["type"] }} {{ field["name"] }} {get;
{{ readonly }} set{
if ({{ field["constraint"] }}){
{{ field["name"] }}=value;
}else {
throw new Exception("Inserted value for {{ field["name"] }} is not valid!");
}
}
}
{% endfor %}
#endregion
}
{% endfor %}
}
this is my question , for generate inner classes, I want to recursively loop on my data model, How I can pass the class["innerClass"] as a parameter to my first for statement?
You can use macros, write a macro for class rendering, and then call it recursively:
{% macro render_class(class) -%}
class {{ class.name }}
{
{% for field in class.fields %}
int {{ field }};
{% endfor %}
{% for subclass in class.subclasses %}
{{ render_class(subclass) }}
{% endfor %}
}
{%- endmacro %}
{% for class in classes %}
{{ render_class(class) }}
{% endfor %}
This works well, but doesn't deal with the proper indentation of subclasses, yielding code like this:
class Bar
{
int meow;
int bark;
class SubBar
{
int joe;
int pete;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With