Tuesday, November 4, 2014

Django Templating Language - Part II

Now let's look at some in-built tags. These will help you arrange data efficiently on your page. These are a lot like XML. However, the syntax is different and it is easier to manage.
If you've noticed, it says Django Templating Language. Thus, as with every other language, this one also has control structures. Let's look at a few.
(Note: We're still learning the language, and even at the end of this post the code will print raw data. I swear, we're really close to rendering data from Python. Just hang tight for one more post.)

FOR:
This simulates a for loop. It is useful when extracting data from a database and rendering on the page, especially when you don't know the number of rows that will be returned. This will simply iterate over the list and render everything.

<html>
{% for row in rows %}
<b><i>{{ row }}</i></b><br>
{% endfor %}
</html>

Let's look at this code step by step. First of all, let's map the for here with that in Python.
In Python:
for i in lst
Thus, i is row, the variable that we will use to iterate over the list of rows that the database returns. lst is rows, the list over which we need to iterate. You can name them whatever you want. Iterating over the list is useless if you don't do anything with the data. As you can see, I've simply printed the value. (As row is a variable, it is enclosed within {{ }}).
Again, this is assuming that each row has only one field. This is seldom the case. We'll see how to render rows with multiple fields when we see Python rendering in general.

IF:
This will simulate an if block. Now, elif won't work in Django 1.3, but it does in 1.6 onwards. If you want an elif statement, just put it under else and then if.
We normally compare two values in if. So Django ships two tags, ifequal and ifnotequal.

<html>
{% ifequal name "tejas" %}
<b><i>{{ name }}</i></b><br>
{% endifequal %}
</html>

<html>
{% ifnotequal name "tejas" %}
<b><i>{{ name }}</i></b><br>
{% endifnotequal %}
</html>

ifequal compares name and "tejas" to see if they're equal. It's Python equivalent would be if name == "tejas". These are the two parameters. They may be variables, strings, or any hard coded values of any data type.

ifnotequal compares name and "tejas" to see if they're not equal. It's Python equivalent would be if name != "tejas".

Great! We've learned the basics of Django's Templating Language. As usual, you can comment or inbox me with your queries. In the next post we see how to actually put data there through Python (Yay!).
You didn't Yay did you? Come on guys, a little more enthusiasm!

No comments:

Post a Comment