1

I have a table that will have varying columns over time and I want my django view to support those changing columns. I also want to use ng-repeat to do some fancy stuff with it such as filtering and other things. However I am having trouble combining the two.

I am passing in the arbitrary col_names with django template language. packages is also sent in with the django template language and is essentially a json array where each row is a dict mapping col_name to some value. i.e.

$scope.packages = [{'col1': 'row1col1', 'col2': 'row2val2'}, {'col1': 'row2col1' .... 

However when I go to put in the rows using packages I can't "nest" my templates. Is there a way to grab arbitrary values out of each row in `packages?

<input ng-model="search" placeholder="Search">
        <table style="width:100%;">
            <thead>
                <tr>
                    <th>Permanent Column 1</th>
                    <th>Permanent Column 2</th>
                    {# changing columns #}
                    {% for col_name in col_names %}
                        <th>{{ col_name }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="package in packages | filter:searchPackage">
                    {% for col_name in columns %}
                        <td>{{package.{{ col_name }}}}</td>  DOESN'T WORK!
                    {% endfor %}
                </tr>
            </tbody>
        </table>

In that problem line I essentially want to have {{package.ACTUAL_ARBITRARY_COL_NAME}} but I don't know how to do that programmatically

bakkal
  • 54,350
  • 12
  • 131
  • 107
sedavidw
  • 11,116
  • 13
  • 61
  • 95

1 Answers1

2

The problem

By default, Django and AngularJS use the same tokens {{ and }} for templating.

So this gets first processed by Django template

{% for col_name in columns %}
    <td>{{package.{{ col_name }}}}</td>  DOESN'T WORK!
        ^                        ^
        |________________________| 
         Django template will try to process this value

Because Django tries to expand what's inside the first {{...}}, you will not get what you want AngularJS to see.

If you want to continue down that road, I suggest you read some solutions to this problem here

Better solution

A better approach is to give AngularJS the items you want Django to loop for you.

$scope.columns = [...];

Then use AngularJS to do all the loops. Whichever way you do it, if you need it done in AngularJS, better do it all in AngularJS and not half-Django half-AngularJS.

Community
  • 1
  • 1
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • totally agree with last statement ... django should be considered as simply a data API. Mixing templating engines is far more trouble than it's worth – charlietfl Jan 18 '16 at 20:52