Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively call a macro in jinja2?

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?

like image 861
Pooya Avatar asked Jul 03 '12 16:07

Pooya


1 Answers

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;
}
}
like image 110
Helgi Avatar answered Nov 10 '22 23:11

Helgi