Quick Django Tip – Modulus
Posted by Shane O'Sullivan on 27 September, 2008
I was fiddling around with Dojo’s Django Templating language (amazingly cool bit of tech of course), and got a bit stuck trying to do something very simple: modulus
All I wanted to do was stripe a list of elements by applying a different class based on whether a row was odd or even. It turns out the reason the answer didn’t really pop up in searches was because, in Django land, it is called divisibleby
So, if you are using a for loop in Django, to check if
(current loop index % 2) == 0
you can use
{{forloop.counter0|divisibleby:2}}
which returns either true or false.
Carl said
You can also use the cycle-tag in the template.
see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#cycle
Shane O'Sullivan said
Hi Carl,
Thanks for the tip, it suits the situation much better. I’ve changed the code to use:
<div class=”{% cycle ‘odd’ ‘even’ %}”>
</div>
Bob said
Hi Shane,
I don’t know if this is the right place to ask, but could you give me a tip to solve this:
Foo bla fla (this is my “fla” query result)
I am using dojox.dtl and dojox.dtl.ext-dojo.NodeList, is there any way to make the html tag to work? Someone in #dojo told me to use dojox.wire, but I think there is a simple solution.
Thanks a lot,
Bob said
WordPress understands the tag, my site not…!:)
Actually this is my result:
Foo bla (tag b)fla(enclosing tag /b)
Bob said
Sorry, I could have used code tag:
Foo bla flaShane O'Sullivan said
hi bob
FYI, to encode a bracket for wordpress use & lt ; withou spaces between.
The code u need is smth like
foo blah <b>{{value}}<b>
And feed the template with the json data
{“value”:”fla”}
Bob said
Hi Shane, Thanks a lot
. The problem that I am facing is that I cannot place the tag inside the json result from dojo.googleSearchStore.
So I have for example:
<div<{{item.content}}</div<
The tags of google results inside the item.content don’t work. The problem is that there are bold tags inside the json data.
Sorry if I can’t explain myself so well.
I appreciate a lot a piece of advice, cause I don’t know what to do anymore.
thanks again
Shane O'Sullivan said
Hi Bob,
The reason that the tags from the JSON don’t work is that DTL automatically escapes them. To disable this behavior, use the ’safe’ command
<div>{{item.content|safe}}</div>
Also, when writing brackets for a blog post, you forgot to put a semi colon after the <. ‘lt’ stands for ‘less than’ so it gives you this <. If you want a greater than bracket, use > ;, to give you >
Bob said
Wow! It worked! Thanks a lot Shane! Next time I won’t forget the semi colon.
By the way, I think your site Chofter.com is a very cool idea. The style is improving a lot too.
Thanks,