views:

243

answers:

2

Hi Guys,

I know django purposely does not allow a whole lot of logic in the templates. However sometimes you are required to evaluate something and based on that change your options.

How do you change a value in a template or insert something only if it's the first record? But you would still like to loop through the rest. For example, my template code below:

    {% for object in object_list %}
     <div id="t{{ object.id }}-header" class="content_headings title_highlight" >{{ object.title }}</div>
     <div id="t{{ object.id }}-content">
         ......

Similar code in a PHP template:

<div id="t<?php if ($i != 1) { echo $i-1; } ?>-header" class="content_headings<?php if ($i == 1) { ?> title_highlight<?php } ?>" ><?php the_title(); ?></div>  
<div id="t<?php if ($i != 1) { echo $i-1; } ?>-content">
+2  A: 
{% for object in object_list %}
<div id="t{{ object.id }}-{%if forloop.first%}header{%else%}content{%endif%}" class="content_headings title_highlight" >{{ object.title }}</div>
...
Tiago
Thanks for the reply, thou the PHP code is not actually doing what you have above. The PHP code is checking if it's the first value, then it's adding a new class. And it outputs an ID for any value > 1 the != -1 bits...
izzy
Hi Issy,I'm sorry, but I don't get what you want to do and why the forloop.first isn't working.Could you clarify?
Tiago
+4  A: 

forloop.first is the way to go. I think all you need to do is slightly change Tiago's answer, and get something like this:

{% for object in object_list %}
    <div id="t{% if not forloop.first %}{{ object.id }}{% endif %}-header" class="content_headings{% if forloop.first %} title_highlight{% endif %}">
        {{ object.title }}
    </div>
    <div id="t{% if not forloop.first %}{{ object.id }}{% endif %}-content">
{% endfor %}

I've checked that against your PHP code and it seems to be doing almost exactly the same (I am not taking 1 from {{ object.id }} because it shouldn't make a difference as long as the IDs are unique, right?)

Thanks that worked, though i think there may be an issue with the JS, it actually wont highlight. So currently using firebug to figure out why the PHP version works but not the django version
izzy
Run the HTML output of the PHP and the HTML output of the Django through a file comparing program (FileMerge if you're on OS X), and see what the differences are. If the JS was working with the PHP-generated HTML then it must be a HTML issue in the Django template. Firebug will probably give you the answer eventually though.
got it working, thanks for the assistance.
izzy