rhblind / django-gcharts

Provides a QuerySet, Manager and other tools for easy integration with the Google Visualization API
Other
41 stars 14 forks source link

Render inside a loop #2

Closed benniel closed 11 years ago

benniel commented 11 years ago

Hi,

I'm trying to render a number charts inside a loop as follows:

    {% gcharts %}
        options = {
            title: "",
            colors: ['#ff9900', '#ffc266', '#ffebcc'],
            is3D: false,
            pieSliceTextStyle: {color: 'black'},
            titleTextStyle: {color: '#46574D', fontSize: '15'},
            pieSliceBorderColor: '#FFF',
            chartArea: {left:50, width:400, top:40, height:140}
        };
        pie_opt = _clone(options);

        {% for pie in charts %}
            pie_opt.title = "{{ pie.title }}";
            container = "pie_chart_{{ forloop.counter }}"

            {% options pie_opt %}
            kind: "PieChart",
                options: pie_opt,
            {% endoptions %}

            {% render container "pie" "pie_opt" %}
        {% endfor %}
    {% endgcharts %}

    {% for pie in charts %}
        <a href=""><div class="pie_chart" id="pie_chart_{{ forloop.counter }}"></div></a>
    {% endfor %}

Everything works, except that the render function doesn't like the container variable. When I look at the generated javascript code, I find:

    opt.container = "container"

How can I make it use my variable as the container id? I need this loop, because I don't know how many graphs will be rendered up front.

rhblind commented 11 years ago

Hi. The issue should be fixed now (in the git version, not the pypi version). The {% render %} tag will try to resolve context variables for the container value, and use it if resolved, otherwise it will use the string literal. You will need to use a little trick to make it work, as the variable needs to be resolvable. Try something like this:

...
{% for pie in charts %}
{% with container=forloop.counter|stringformat:"s"|add:"_pie_chart" %}
    ...
    do some stuff
    ...

    {% render container pie pie_opt %}

{% endwith %}
{% endfor %}

{% endgcharts %}

{% for pie in charts %}
    <a href=""><div class="pie_chart" id="{{ forloop.counter }}_pie_chart"></div></a>
{% endfor%}

Note that the naming of the container variable is backwards from what you originally had, due to the stringformat filter in the with tag.

Hope you work it out! Cheers

benniel commented 11 years ago

Perfect. Thank you! :)