Saturday, June 26, 2010

include and ifchanged inconsistent behavior (variables vs. strings)

I often loop through lists, but for the guts of the list use "include"
because the same code is needed in multiple places.

Inside the included files, "ifchanged" works, but only as long as the
include is done by way of a string. I recently changed a template that
was a complex mess of IFs to instead use template inheritance and have
my page object return the appropriate template to include, and
ifchanged stopped working.

Simple example:

MODELS.PY

class Page(models.Model):
...
def worlds(self):
return ['Mercury', 'Venus', 'Venus', 'Earth', 'Earth', 'Earth',
'Mars', 'Mars', 'Mars', 'Mars']

def helloTemplate(self):
return 'test/world.html'


VIEWS.PY

def test(request):
page = Page.objects.get(slug='mimsy') #just to get an object with
those methods on it
return render_to_response('test/hello.html', {'page': page})


TEST/HELLO.HTML

<h2>As string</h2>

{% for world in page.worlds %}
{% include "test/world.html" %}
{% endfor %}

<h2>As variable</h2>

{% for world in page.worlds %}
{% include page.helloTemplate %}
{% endfor %}

TEST/WORLD.HTML

{% ifchanged %}Hello {{ world }}<br />{% endifchanged %}

RESULT:

As string

Hello Mercury
Hello Venus
Hello Earth
Hello Mars


As variable

Hello Mercury
Hello Venus
Hello Venus
Hello Earth
Hello Earth
Hello Earth
Hello Mars
Hello Mars
Hello Mars
Hello Mars

Is this a bug? And if it is, which of those results is correct?

Here's my real-world example:

def linkDefinition(self):
return 'parts/dd/' + self.organize_URLs_by + '.html'


{% for link in links %}
{% include page.linkDefinition %}
{% endfor %}

vs.

{% for link in links %}
{% ifequal page.linkDefinition "parts/dd/title.html" %}
{% include "parts/dd/title.html" %}
{% else %}
{% ifequal page.linkDefinition "parts/dd/category.html" %}
{% include "parts/dd/category.html" %}
{% else %}
{% ifequal page.linkDefinition "parts/dd/author.html" %}
{% include "parts/dd/author.html" %}
{% else %}
{% ifequal page.linkDefinition "parts/dd/content.html" %}
{% include "parts/dd/content.html" %}
{% else %}
{% ifequal page.linkDefinition "parts/dd/d6-icon.html" %}
{% include "parts/dd/d6-icon.html" %}
{% endifequal %}
{% endifequal %}
{% endifequal %}
{% endifequal %}
{% endifequal %}
{% endfor %}

I can move that mess off into its own include file (I've tested it),
but can I even do an include inside of a loop and expect ifchanged to
work in the future?

Jerry

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment